1//===-- TypeSystemClang.cpp -----------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "TypeSystemClang.h"
10
11#include "llvm/Support/FormatAdapters.h"
12#include "llvm/Support/FormatVariadic.h"
13
14#include <mutex>
15#include <string>
16#include <vector>
17
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/ASTImporter.h"
20#include "clang/AST/Attr.h"
21#include "clang/AST/CXXInheritance.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclTemplate.h"
24#include "clang/AST/Mangle.h"
25#include "clang/AST/RecordLayout.h"
26#include "clang/AST/Type.h"
27#include "clang/AST/VTableBuilder.h"
28#include "clang/Basic/Builtins.h"
29#include "clang/Basic/Diagnostic.h"
30#include "clang/Basic/FileManager.h"
31#include "clang/Basic/FileSystemOptions.h"
32#include "clang/Basic/LangStandard.h"
33#include "clang/Basic/SourceManager.h"
34#include "clang/Basic/TargetInfo.h"
35#include "clang/Basic/TargetOptions.h"
36#include "clang/Frontend/FrontendOptions.h"
37#include "clang/Lex/HeaderSearch.h"
38#include "clang/Lex/HeaderSearchOptions.h"
39#include "clang/Lex/ModuleMap.h"
40#include "clang/Sema/Sema.h"
41
42#include "llvm/Support/Signals.h"
43#include "llvm/Support/Threading.h"
44
45#include "Plugins/ExpressionParser/Clang/ClangASTImporter.h"
46#include "Plugins/ExpressionParser/Clang/ClangASTMetadata.h"
47#include "Plugins/ExpressionParser/Clang/ClangExternalASTSourceCallbacks.h"
48#include "Plugins/ExpressionParser/Clang/ClangFunctionCaller.h"
49#include "Plugins/ExpressionParser/Clang/ClangPersistentVariables.h"
50#include "Plugins/ExpressionParser/Clang/ClangUserExpression.h"
51#include "Plugins/ExpressionParser/Clang/ClangUtil.h"
52#include "Plugins/ExpressionParser/Clang/ClangUtilityFunction.h"
53#include "lldb/Utility/ArchSpec.h"
54#include "lldb/Utility/Flags.h"
55
56#include "lldb/Core/DumpDataExtractor.h"
57#include "lldb/Core/Module.h"
58#include "lldb/Core/PluginManager.h"
59#include "lldb/Core/StreamFile.h"
60#include "lldb/Core/ThreadSafeDenseMap.h"
61#include "lldb/Core/UniqueCStringMap.h"
62#include "lldb/Symbol/ObjectFile.h"
63#include "lldb/Symbol/SymbolFile.h"
64#include "lldb/Target/ExecutionContext.h"
65#include "lldb/Target/Language.h"
66#include "lldb/Target/Process.h"
67#include "lldb/Target/Target.h"
68#include "lldb/Utility/DataExtractor.h"
69#include "lldb/Utility/LLDBAssert.h"
70#include "lldb/Utility/Log.h"
71#include "lldb/Utility/RegularExpression.h"
72#include "lldb/Utility/Scalar.h"
73
74#include "Plugins/LanguageRuntime/ObjC/ObjCLanguageRuntime.h"
75#include "Plugins/SymbolFile/DWARF/DWARFASTParserClang.h"
76#include "Plugins/SymbolFile/PDB/PDBASTParser.h"
77
78#include <stdio.h>
79
80#include <mutex>
81
82using namespace lldb;
83using namespace lldb_private;
84using namespace clang;
85using llvm::StringSwitch;
86
87LLDB_PLUGIN_DEFINE(TypeSystemClang)
88
89namespace {
90static void VerifyDecl(clang::Decl *decl) {
91 assert(decl && "VerifyDecl called with nullptr?");
92#ifndef NDEBUG
93 // We don't care about the actual access value here but only want to trigger
94 // that Clang calls its internal Decl::AccessDeclContextSanity check.
95 decl->getAccess();
96#endif
97}
98
99static inline bool
100TypeSystemClangSupportsLanguage(lldb::LanguageType language) {
101 return language == eLanguageTypeUnknown || // Clang is the default type system
102 lldb_private::Language::LanguageIsC(language) ||
103 lldb_private::Language::LanguageIsCPlusPlus(language) ||
104 lldb_private::Language::LanguageIsObjC(language) ||
105 lldb_private::Language::LanguageIsPascal(language) ||
106 // Use Clang for Rust until there is a proper language plugin for it
107 language == eLanguageTypeRust ||
108 language == eLanguageTypeExtRenderScript ||
109 // Use Clang for D until there is a proper language plugin for it
110 language == eLanguageTypeD ||
111 // Open Dylan compiler debug info is designed to be Clang-compatible
112 language == eLanguageTypeDylan;
113}
114
115// Checks whether m1 is an overload of m2 (as opposed to an override). This is
116// called by addOverridesForMethod to distinguish overrides (which share a
117// vtable entry) from overloads (which require distinct entries).
118bool isOverload(clang::CXXMethodDecl *m1, clang::CXXMethodDecl *m2) {
119 // FIXME: This should detect covariant return types, but currently doesn't.
120 lldbassert(&m1->getASTContext() == &m2->getASTContext() &&
121 "Methods should have the same AST context");
122 clang::ASTContext &context = m1->getASTContext();
123
124 const auto *m1Type = llvm::cast<clang::FunctionProtoType>(
125 context.getCanonicalType(m1->getType()));
126
127 const auto *m2Type = llvm::cast<clang::FunctionProtoType>(
128 context.getCanonicalType(m2->getType()));
129
130 auto compareArgTypes = [&context](const clang::QualType &m1p,
131 const clang::QualType &m2p) {
132 return context.hasSameType(m1p.getUnqualifiedType(),
133 m2p.getUnqualifiedType());
134 };
135
136 // FIXME: In C++14 and later, we can just pass m2Type->param_type_end()
137 // as a fourth parameter to std::equal().
138 return (m1->getNumParams() != m2->getNumParams()) ||
139 !std::equal(m1Type->param_type_begin(), m1Type->param_type_end(),
140 m2Type->param_type_begin(), compareArgTypes);
141}
142
143// If decl is a virtual method, walk the base classes looking for methods that
144// decl overrides. This table of overridden methods is used by IRGen to
145// determine the vtable layout for decl's parent class.
146void addOverridesForMethod(clang::CXXMethodDecl *decl) {
147 if (!decl->isVirtual())
148 return;
149
150 clang::CXXBasePaths paths;
151 llvm::SmallVector<clang::NamedDecl *, 4> decls;
152
153 auto find_overridden_methods =
154 [&decls, decl](const clang::CXXBaseSpecifier *specifier,
155 clang::CXXBasePath &path) {
156 if (auto *base_record = llvm::dyn_cast<clang::CXXRecordDecl>(
157 specifier->getType()->getAs<clang::RecordType>()->getDecl())) {
158
159 clang::DeclarationName name = decl->getDeclName();
160
161 // If this is a destructor, check whether the base class destructor is
162 // virtual.
163 if (name.getNameKind() == clang::DeclarationName::CXXDestructorName)
164 if (auto *baseDtorDecl = base_record->getDestructor()) {
165 if (baseDtorDecl->isVirtual()) {
166 path.Decls = baseDtorDecl;
167 decls.push_back(baseDtorDecl);
168 return true;
169 } else
170 return false;
171 }
172
173 // Otherwise, search for name in the base class.
174 for (path.Decls = base_record->lookup(name); !path.Decls.empty();
175 path.Decls = path.Decls.slice(1)) {
176 if (auto *method_decl =
177 llvm::dyn_cast<clang::CXXMethodDecl>(path.Decls.front()))
178 if (method_decl->isVirtual() && !isOverload(decl, method_decl)) {
179 path.Decls = method_decl;
180 decls.push_back(method_decl);
181 return true;
182 }
183 }
184 }
185
186 return false;
187 };
188
189 if (decl->getParent()->lookupInBases(find_overridden_methods, paths)) {
190 for (auto *overridden_decl : decls)
191 decl->addOverriddenMethod(
192 llvm::cast<clang::CXXMethodDecl>(overridden_decl));
193 }
194}
195}
196
197static lldb::addr_t GetVTableAddress(Process &process,
198 VTableContextBase &vtable_ctx,
199 ValueObject &valobj,
200 const ASTRecordLayout &record_layout) {
201 // Retrieve type info
202 CompilerType pointee_type;
203 CompilerType this_type(valobj.GetCompilerType());
204 uint32_t type_info = this_type.GetTypeInfo(&pointee_type);
205 if (!type_info)
206 return LLDB_INVALID_ADDRESS;
207
208 // Check if it's a pointer or reference
209 bool ptr_or_ref = false;
210 if (type_info & (eTypeIsPointer | eTypeIsReference)) {
211 ptr_or_ref = true;
212 type_info = pointee_type.GetTypeInfo();
213 }
214
215 // We process only C++ classes
216 const uint32_t cpp_class = eTypeIsClass | eTypeIsCPlusPlus;
217 if ((type_info & cpp_class) != cpp_class)
218 return LLDB_INVALID_ADDRESS;
219
220 // Calculate offset to VTable pointer
221 lldb::offset_t vbtable_ptr_offset =
222 vtable_ctx.isMicrosoft() ? record_layout.getVBPtrOffset().getQuantity()
223 : 0;
224
225 if (ptr_or_ref) {
226 // We have a pointer / ref to object, so read
227 // VTable pointer from process memory
228
229 if (valobj.GetAddressTypeOfChildren() != eAddressTypeLoad)
230 return LLDB_INVALID_ADDRESS;
231
232 auto vbtable_ptr_addr = valobj.GetValueAsUnsigned(LLDB_INVALID_ADDRESS);
233 if (vbtable_ptr_addr == LLDB_INVALID_ADDRESS)
234 return LLDB_INVALID_ADDRESS;
235
236 vbtable_ptr_addr += vbtable_ptr_offset;
237
238 Status err;
239 return process.ReadPointerFromMemory(vbtable_ptr_addr, err);
240 }
241
242 // We have an object already read from process memory,
243 // so just extract VTable pointer from it
244
245 DataExtractor data;
246 Status err;
247 auto size = valobj.GetData(data, err);
248 if (err.Fail() || vbtable_ptr_offset + data.GetAddressByteSize() > size)
249 return LLDB_INVALID_ADDRESS;
250
251 return data.GetAddress(&vbtable_ptr_offset);
252}
253
254static int64_t ReadVBaseOffsetFromVTable(Process &process,
255 VTableContextBase &vtable_ctx,
256 lldb::addr_t vtable_ptr,
257 const CXXRecordDecl *cxx_record_decl,
258 const CXXRecordDecl *base_class_decl) {
259 if (vtable_ctx.isMicrosoft()) {
260 clang::MicrosoftVTableContext &msoft_vtable_ctx =
261 static_cast<clang::MicrosoftVTableContext &>(vtable_ctx);
262
263 // Get the index into the virtual base table. The
264 // index is the index in uint32_t from vbtable_ptr
265 const unsigned vbtable_index =
266 msoft_vtable_ctx.getVBTableIndex(cxx_record_decl, base_class_decl);
267 const lldb::addr_t base_offset_addr = vtable_ptr + vbtable_index * 4;
268 Status err;
269 return process.ReadSignedIntegerFromMemory(base_offset_addr, 4, INT64_MAX,
270 err);
271 }
272
273 clang::ItaniumVTableContext &itanium_vtable_ctx =
274 static_cast<clang::ItaniumVTableContext &>(vtable_ctx);
275
276 clang::CharUnits base_offset_offset =
277 itanium_vtable_ctx.getVirtualBaseOffsetOffset(cxx_record_decl,
278 base_class_decl);
279 const lldb::addr_t base_offset_addr =
280 vtable_ptr + base_offset_offset.getQuantity();
281 const uint32_t base_offset_size = process.GetAddressByteSize();
282 Status err;
283 return process.ReadSignedIntegerFromMemory(base_offset_addr, base_offset_size,
284 INT64_MAX, err);
285}
286
287static bool GetVBaseBitOffset(VTableContextBase &vtable_ctx,
288 ValueObject &valobj,
289 const ASTRecordLayout &record_layout,
290 const CXXRecordDecl *cxx_record_decl,
291 const CXXRecordDecl *base_class_decl,
292 int32_t &bit_offset) {
293 ExecutionContext exe_ctx(valobj.GetExecutionContextRef());
294 Process *process = exe_ctx.GetProcessPtr();
295 if (!process)
296 return false;
297
298 lldb::addr_t vtable_ptr =
299 GetVTableAddress(*process, vtable_ctx, valobj, record_layout);
300 if (vtable_ptr == LLDB_INVALID_ADDRESS)
301 return false;
302
303 auto base_offset = ReadVBaseOffsetFromVTable(
304 *process, vtable_ctx, vtable_ptr, cxx_record_decl, base_class_decl);
305 if (base_offset == INT64_MAX)
306 return false;
307
308 bit_offset = base_offset * 8;
309
310 return true;
311}
312
313typedef lldb_private::ThreadSafeDenseMap<clang::ASTContext *, TypeSystemClang *>
314 ClangASTMap;
315
316static ClangASTMap &GetASTMap() {
317 static ClangASTMap *g_map_ptr = nullptr;
318 static llvm::once_flag g_once_flag;
319 llvm::call_once(g_once_flag, []() {
320 g_map_ptr = new ClangASTMap(); // leaked on purpose to avoid spins
321 });
322 return *g_map_ptr;
323}
324
325TypePayloadClang::TypePayloadClang(OptionalClangModuleID owning_module,
326 bool is_complete_objc_class)
327 : m_payload(owning_module.GetValue()) {
328 SetIsCompleteObjCClass(is_complete_objc_class);
329}
330
331void TypePayloadClang::SetOwningModule(OptionalClangModuleID id) {
332 assert(id.GetValue() < ObjCClassBit);
333 bool is_complete = IsCompleteObjCClass();
334 m_payload = id.GetValue();
335 SetIsCompleteObjCClass(is_complete);
336}
337
338static void SetMemberOwningModule(clang::Decl *member,
339 const clang::Decl *parent) {
340 if (!member || !parent)
341 return;
342
343 OptionalClangModuleID id(parent->getOwningModuleID());
344 if (!id.HasValue())
345 return;
346
347 member->setFromASTFile();
348 member->setOwningModuleID(id.GetValue());
349 member->setModuleOwnershipKind(clang::Decl::ModuleOwnershipKind::Visible);
350 if (llvm::isa<clang::NamedDecl>(member))
351 if (auto *dc = llvm::dyn_cast<clang::DeclContext>(parent)) {
352 dc->setHasExternalVisibleStorage(true);
353 // This triggers ExternalASTSource::FindExternalVisibleDeclsByName() to be
354 // called when searching for members.
355 dc->setHasExternalLexicalStorage(true);
356 }
357}
358
359char TypeSystemClang::ID;
360
361bool TypeSystemClang::IsOperator(llvm::StringRef name,
362 clang::OverloadedOperatorKind &op_kind) {
363 // All operators have to start with "operator".
364 if (!name.consume_front("operator"))
365 return false;
366
367 // Remember if there was a space after "operator". This is necessary to
368 // check for collisions with strangely named functions like "operatorint()".
369 bool space_after_operator = name.consume_front(" ");
370
371 op_kind = StringSwitch<clang::OverloadedOperatorKind>(name)
372 .Case("+", clang::OO_Plus)
373 .Case("+=", clang::OO_PlusEqual)
374 .Case("++", clang::OO_PlusPlus)
375 .Case("-", clang::OO_Minus)
376 .Case("-=", clang::OO_MinusEqual)
377 .Case("--", clang::OO_MinusMinus)
378 .Case("->", clang::OO_Arrow)
379 .Case("->*", clang::OO_ArrowStar)
380 .Case("*", clang::OO_Star)
381 .Case("*=", clang::OO_StarEqual)
382 .Case("/", clang::OO_Slash)
383 .Case("/=", clang::OO_SlashEqual)
384 .Case("%", clang::OO_Percent)
385 .Case("%=", clang::OO_PercentEqual)
386 .Case("^", clang::OO_Caret)
387 .Case("^=", clang::OO_CaretEqual)
388 .Case("&", clang::OO_Amp)
389 .Case("&=", clang::OO_AmpEqual)
390 .Case("&&", clang::OO_AmpAmp)
391 .Case("|", clang::OO_Pipe)
392 .Case("|=", clang::OO_PipeEqual)
393 .Case("||", clang::OO_PipePipe)
394 .Case("~", clang::OO_Tilde)
395 .Case("!", clang::OO_Exclaim)
396 .Case("!=", clang::OO_ExclaimEqual)
397 .Case("=", clang::OO_Equal)
398 .Case("==", clang::OO_EqualEqual)
399 .Case("<", clang::OO_Less)
400 .Case("<<", clang::OO_LessLess)
401 .Case("<<=", clang::OO_LessLessEqual)
402 .Case("<=", clang::OO_LessEqual)
403 .Case(">", clang::OO_Greater)
404 .Case(">>", clang::OO_GreaterGreater)
405 .Case(">>=", clang::OO_GreaterGreaterEqual)
406 .Case(">=", clang::OO_GreaterEqual)
407 .Case("()", clang::OO_Call)
408 .Case("[]", clang::OO_Subscript)
409 .Case(",", clang::OO_Comma)
410 .Default(clang::NUM_OVERLOADED_OPERATORS);
411
412 // We found a fitting operator, so we can exit now.
413 if (op_kind != clang::NUM_OVERLOADED_OPERATORS)
414 return true;
415
416 // After the "operator " or "operator" part is something unknown. This means
417 // it's either one of the named operators (new/delete), a conversion operator
418 // (e.g. operator bool) or a function which name starts with "operator"
419 // (e.g. void operatorbool).
420
421 // If it's a function that starts with operator it can't have a space after
422 // "operator" because identifiers can't contain spaces.
423 // E.g. "operator int" (conversion operator)
424 // vs. "operatorint" (function with colliding name).
425 if (!space_after_operator)
426 return false; // not an operator.
427
428 // Now the operator is either one of the named operators or a conversion
429 // operator.
430 op_kind = StringSwitch<clang::OverloadedOperatorKind>(name)
431 .Case("new", clang::OO_New)
432 .Case("new[]", clang::OO_Array_New)
433 .Case("delete", clang::OO_Delete)
434 .Case("delete[]", clang::OO_Array_Delete)
435 // conversion operators hit this case.
436 .Default(clang::NUM_OVERLOADED_OPERATORS);
437
438 return true;
439}
440
441clang::AccessSpecifier
442TypeSystemClang::ConvertAccessTypeToAccessSpecifier(AccessType access) {
443 switch (access) {
444 default:
445 break;
446 case eAccessNone:
447 return AS_none;
448 case eAccessPublic:
449 return AS_public;
450 case eAccessPrivate:
451 return AS_private;
452 case eAccessProtected:
453 return AS_protected;
454 }
455 return AS_none;
456}
457
458static void ParseLangArgs(LangOptions &Opts, InputKind IK, const char *triple) {
459 // FIXME: Cleanup per-file based stuff.
460
461 // Set some properties which depend solely on the input kind; it would be
462 // nice to move these to the language standard, and have the driver resolve
463 // the input kind + language standard.
464 if (IK.getLanguage() == clang::Language::Asm) {
465 Opts.AsmPreprocessor = 1;
466 } else if (IK.isObjectiveC()) {
467 Opts.ObjC = 1;
468 }
469
470 LangStandard::Kind LangStd = LangStandard::lang_unspecified;
471
472 if (LangStd == LangStandard::lang_unspecified) {
473 // Based on the base language, pick one.
474 switch (IK.getLanguage()) {
475 case clang::Language::Unknown:
476 case clang::Language::LLVM_IR:
477 case clang::Language::RenderScript:
478 llvm_unreachable("Invalid input kind!");
479 case clang::Language::OpenCL:
480 LangStd = LangStandard::lang_opencl10;
481 break;
482 case clang::Language::CUDA:
483 LangStd = LangStandard::lang_cuda;
484 break;
485 case clang::Language::Asm:
486 case clang::Language::C:
487 case clang::Language::ObjC:
488 LangStd = LangStandard::lang_gnu99;
489 break;
490 case clang::Language::CXX:
491 case clang::Language::ObjCXX:
492 LangStd = LangStandard::lang_gnucxx98;
493 break;
494 case clang::Language::HIP:
495 LangStd = LangStandard::lang_hip;
496 break;
497 }
498 }
499
500 const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
501 Opts.LineComment = Std.hasLineComments();
502 Opts.C99 = Std.isC99();
503 Opts.CPlusPlus = Std.isCPlusPlus();
504 Opts.CPlusPlus11 = Std.isCPlusPlus11();
505 Opts.Digraphs = Std.hasDigraphs();
506 Opts.GNUMode = Std.isGNUMode();
507 Opts.GNUInline = !Std.isC99();
508 Opts.HexFloats = Std.hasHexFloats();
509 Opts.ImplicitInt = Std.hasImplicitInt();
510
511 Opts.WChar = true;
512
513 // OpenCL has some additional defaults.
514 if (LangStd == LangStandard::lang_opencl10) {
515 Opts.OpenCL = 1;
516 Opts.AltiVec = 1;
517 Opts.CXXOperatorNames = 1;
518 Opts.setLaxVectorConversions(LangOptions::LaxVectorConversionKind::All);
519 }
520
521 // OpenCL and C++ both have bool, true, false keywords.
522 Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
523
524 Opts.setValueVisibilityMode(DefaultVisibility);
525
526 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs is
527 // specified, or -std is set to a conforming mode.
528 Opts.Trigraphs = !Opts.GNUMode;
529 Opts.CharIsSigned = ArchSpec(triple).CharIsSignedByDefault();
530 Opts.OptimizeSize = 0;
531
532 // FIXME: Eliminate this dependency.
533 // unsigned Opt =
534 // Args.hasArg(OPT_Os) ? 2 : getLastArgIntValue(Args, OPT_O, 0, Diags);
535 // Opts.Optimize = Opt != 0;
536 unsigned Opt = 0;
537
538 // This is the __NO_INLINE__ define, which just depends on things like the
539 // optimization level and -fno-inline, not actually whether the backend has
540 // inlining enabled.
541 //
542 // FIXME: This is affected by other options (-fno-inline).
543 Opts.NoInlineDefine = !Opt;
544
545 // This is needed to allocate the extra space for the owning module
546 // on each decl.
547 Opts.ModulesLocalVisibility = 1;
548}
549
550TypeSystemClang::TypeSystemClang(llvm::StringRef name,
551 llvm::Triple target_triple) {
552 m_display_name = name.str();
553 if (!target_triple.str().empty())
554 SetTargetTriple(target_triple.str());
555 // The caller didn't pass an ASTContext so create a new one for this
556 // TypeSystemClang.
557 CreateASTContext();
558}
559
560TypeSystemClang::TypeSystemClang(llvm::StringRef name,
561 ASTContext &existing_ctxt) {
562 m_display_name = name.str();
563 SetTargetTriple(existing_ctxt.getTargetInfo().getTriple().str());
564
565 m_ast_up.reset(&existing_ctxt);
566 GetASTMap().Insert(&existing_ctxt, this);
567}
568
569// Destructor
570TypeSystemClang::~TypeSystemClang() { Finalize(); }
571
572ConstString TypeSystemClang::GetPluginNameStatic() {
573 return ConstString("clang");
574}
575
576ConstString TypeSystemClang::GetPluginName() {
577 return TypeSystemClang::GetPluginNameStatic();
578}
579
580uint32_t TypeSystemClang::GetPluginVersion() { return 1; }
581
582lldb::TypeSystemSP TypeSystemClang::CreateInstance(lldb::LanguageType language,
583 lldb_private::Module *module,
584 Target *target) {
585 if (!TypeSystemClangSupportsLanguage(language))
586 return lldb::TypeSystemSP();
587 ArchSpec arch;
588 if (module)
589 arch = module->GetArchitecture();
590 else if (target)
591 arch = target->GetArchitecture();
592
593 if (!arch.IsValid())
594 return lldb::TypeSystemSP();
595
596 llvm::Triple triple = arch.GetTriple();
597 // LLVM wants this to be set to iOS or MacOSX; if we're working on
598 // a bare-boards type image, change the triple for llvm's benefit.
599 if (triple.getVendor() == llvm::Triple::Apple &&
600 triple.getOS() == llvm::Triple::UnknownOS) {
601 if (triple.getArch() == llvm::Triple::arm ||
602 triple.getArch() == llvm::Triple::aarch64 ||
603 triple.getArch() == llvm::Triple::aarch64_32 ||
604 triple.getArch() == llvm::Triple::thumb) {
605 triple.setOS(llvm::Triple::IOS);
606 } else {
607 triple.setOS(llvm::Triple::MacOSX);
608 }
609 }
610
611 if (module) {
612 std::string ast_name =
613 "ASTContext for '" + module->GetFileSpec().GetPath() + "'";
614 return std::make_shared<TypeSystemClang>(ast_name, triple);
615 } else if (target && target->IsValid())
616 return std::make_shared<ScratchTypeSystemClang>(*target, triple);
617 return lldb::TypeSystemSP();
618}
619
620LanguageSet TypeSystemClang::GetSupportedLanguagesForTypes() {
621 LanguageSet languages;
622 languages.Insert(lldb::eLanguageTypeC89);
623 languages.Insert(lldb::eLanguageTypeC);
624 languages.Insert(lldb::eLanguageTypeC11);
625 languages.Insert(lldb::eLanguageTypeC_plus_plus);
626 languages.Insert(lldb::eLanguageTypeC99);
627 languages.Insert(lldb::eLanguageTypeObjC);
628 languages.Insert(lldb::eLanguageTypeObjC_plus_plus);
629 languages.Insert(lldb::eLanguageTypeC_plus_plus_03);
630 languages.Insert(lldb::eLanguageTypeC_plus_plus_11);
631 languages.Insert(lldb::eLanguageTypeC11);
632 languages.Insert(lldb::eLanguageTypeC_plus_plus_14);
633 return languages;
634}
635
636LanguageSet TypeSystemClang::GetSupportedLanguagesForExpressions() {
637 LanguageSet languages;
638 languages.Insert(lldb::eLanguageTypeC_plus_plus);
639 languages.Insert(lldb::eLanguageTypeObjC_plus_plus);
640 languages.Insert(lldb::eLanguageTypeC_plus_plus_03);
641 languages.Insert(lldb::eLanguageTypeC_plus_plus_11);
642 languages.Insert(lldb::eLanguageTypeC_plus_plus_14);
643 return languages;
644}
645
646void TypeSystemClang::Initialize() {
647 PluginManager::RegisterPlugin(
648 GetPluginNameStatic(), "clang base AST context plug-in", CreateInstance,
649 GetSupportedLanguagesForTypes(), GetSupportedLanguagesForExpressions());
650}
651
652void TypeSystemClang::Terminate() {
653 PluginManager::UnregisterPlugin(CreateInstance);
654}
655
656void TypeSystemClang::Finalize() {
657 assert(m_ast_up);
658 GetASTMap().Erase(m_ast_up.get());
659 if (!m_ast_owned)
660 m_ast_up.release();
661
662 m_builtins_up.reset();
663 m_selector_table_up.reset();
664 m_identifier_table_up.reset();
665 m_target_info_up.reset();
666 m_target_options_rp.reset();
667 m_diagnostics_engine_up.reset();
668 m_source_manager_up.reset();
669 m_language_options_up.reset();
670}
671
672void TypeSystemClang::setSema(Sema *s) {
673 // Ensure that the new sema actually belongs to our ASTContext.
674 assert(s == nullptr || &s->getASTContext() == m_ast_up.get());
675 m_sema = s;
676}
677
678const char *TypeSystemClang::GetTargetTriple() {
679 return m_target_triple.c_str();
680}
681
682void TypeSystemClang::SetTargetTriple(llvm::StringRef target_triple) {
683 m_target_triple = target_triple.str();
684}
685
686void TypeSystemClang::SetExternalSource(
687 llvm::IntrusiveRefCntPtr<ExternalASTSource> &ast_source_up) {
688 ASTContext &ast = getASTContext();
689 ast.setExternalSource(ast_source_up);
690 ast.getTranslationUnitDecl()->setHasExternalLexicalStorage(true);
691}
692
693ASTContext &TypeSystemClang::getASTContext() {
694 assert(m_ast_up);
695 return *m_ast_up;
696}
697
698class NullDiagnosticConsumer : public DiagnosticConsumer {
699public:
700 NullDiagnosticConsumer() {
701 m_log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS);
702 }
703
704 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
705 const clang::Diagnostic &info) override {
706 if (m_log) {
707 llvm::SmallVector<char, 32> diag_str(10);
708 info.FormatDiagnostic(diag_str);
709 diag_str.push_back('\0');
710 LLDB_LOGF(m_log, "Compiler diagnostic: %s\n", diag_str.data());
711 }
712 }
713
714 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
715 return new NullDiagnosticConsumer();
716 }
717
718private:
719 Log *m_log;
720};
721
722void TypeSystemClang::CreateASTContext() {
723 assert(!m_ast_up);
724 m_ast_owned = true;
725
726 m_language_options_up = std::make_unique<LangOptions>();
727 ParseLangArgs(*m_language_options_up, clang::Language::ObjCXX,
728 GetTargetTriple());
729
730 m_identifier_table_up =
731 std::make_unique<IdentifierTable>(*m_language_options_up, nullptr);
732 m_builtins_up = std::make_unique<Builtin::Context>();
733
734 m_selector_table_up = std::make_unique<SelectorTable>();
735
736 clang::FileSystemOptions file_system_options;
737 m_file_manager_up = std::make_unique<clang::FileManager>(
738 file_system_options, FileSystem::Instance().GetVirtualFileSystem());
739
740 llvm::IntrusiveRefCntPtr<DiagnosticIDs> diag_id_sp(new DiagnosticIDs());
741 m_diagnostics_engine_up =
742 std::make_unique<DiagnosticsEngine>(diag_id_sp, new DiagnosticOptions());
743
744 m_source_manager_up = std::make_unique<clang::SourceManager>(
745 *m_diagnostics_engine_up, *m_file_manager_up);
746 m_ast_up = std::make_unique<ASTContext>(
747 *m_language_options_up, *m_source_manager_up, *m_identifier_table_up,
748 *m_selector_table_up, *m_builtins_up);
749
750 m_diagnostic_consumer_up = std::make_unique<NullDiagnosticConsumer>();
751 m_ast_up->getDiagnostics().setClient(m_diagnostic_consumer_up.get(), false);
752
753 // This can be NULL if we don't know anything about the architecture or if
754 // the target for an architecture isn't enabled in the llvm/clang that we
755 // built
756 TargetInfo *target_info = getTargetInfo();
757 if (target_info)
758 m_ast_up->InitBuiltinTypes(*target_info);
759
760 GetASTMap().Insert(m_ast_up.get(), this);
761
762 llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source_up(
763 new ClangExternalASTSourceCallbacks(*this));
764 SetExternalSource(ast_source_up);
765}
766
767TypeSystemClang *TypeSystemClang::GetASTContext(clang::ASTContext *ast) {
768 TypeSystemClang *clang_ast = GetASTMap().Lookup(ast);
769 return clang_ast;
770}
771
772clang::MangleContext *TypeSystemClang::getMangleContext() {
773 if (m_mangle_ctx_up == nullptr)
774 m_mangle_ctx_up.reset(getASTContext().createMangleContext());
775 return m_mangle_ctx_up.get();
776}
777
778std::shared_ptr<clang::TargetOptions> &TypeSystemClang::getTargetOptions() {
779 if (m_target_options_rp == nullptr && !m_target_triple.empty()) {
780 m_target_options_rp = std::make_shared<clang::TargetOptions>();
781 if (m_target_options_rp != nullptr)
782 m_target_options_rp->Triple = m_target_triple;
783 }
784 return m_target_options_rp;
785}
786
787TargetInfo *TypeSystemClang::getTargetInfo() {
788 // target_triple should be something like "x86_64-apple-macosx"
789 if (m_target_info_up == nullptr && !m_target_triple.empty())
790 m_target_info_up.reset(TargetInfo::CreateTargetInfo(
791 getASTContext().getDiagnostics(), getTargetOptions()));
792 return m_target_info_up.get();
793}
794
795#pragma mark Basic Types
796
797static inline bool QualTypeMatchesBitSize(const uint64_t bit_size,
798 ASTContext &ast, QualType qual_type) {
799 uint64_t qual_type_bit_size = ast.getTypeSize(qual_type);
800 return qual_type_bit_size == bit_size;
801}
802
803CompilerType
804TypeSystemClang::GetBuiltinTypeForEncodingAndBitSize(Encoding encoding,
805 size_t bit_size) {
806 ASTContext &ast = getASTContext();
807 switch (encoding) {
808 case eEncodingInvalid:
809 if (QualTypeMatchesBitSize(bit_size, ast, ast.VoidPtrTy))
810 return GetType(ast.VoidPtrTy);
811 break;
812
813 case eEncodingUint:
814 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy))
815 return GetType(ast.UnsignedCharTy);
816 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy))
817 return GetType(ast.UnsignedShortTy);
818 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedIntTy))
819 return GetType(ast.UnsignedIntTy);
820 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongTy))
821 return GetType(ast.UnsignedLongTy);
822 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongLongTy))
823 return GetType(ast.UnsignedLongLongTy);
824 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedInt128Ty))
825 return GetType(ast.UnsignedInt128Ty);
826 break;
827
828 case eEncodingSint:
829 if (QualTypeMatchesBitSize(bit_size, ast, ast.SignedCharTy))
830 return GetType(ast.SignedCharTy);
831 if (QualTypeMatchesBitSize(bit_size, ast, ast.ShortTy))
832 return GetType(ast.ShortTy);
833 if (QualTypeMatchesBitSize(bit_size, ast, ast.IntTy))
834 return GetType(ast.IntTy);
835 if (QualTypeMatchesBitSize(bit_size, ast, ast.LongTy))
836 return GetType(ast.LongTy);
837 if (QualTypeMatchesBitSize(bit_size, ast, ast.LongLongTy))
838 return GetType(ast.LongLongTy);
839 if (QualTypeMatchesBitSize(bit_size, ast, ast.Int128Ty))
840 return GetType(ast.Int128Ty);
841 break;
842
843 case eEncodingIEEE754:
844 if (QualTypeMatchesBitSize(bit_size, ast, ast.FloatTy))
845 return GetType(ast.FloatTy);
846 if (QualTypeMatchesBitSize(bit_size, ast, ast.DoubleTy))
847 return GetType(ast.DoubleTy);
848 if (QualTypeMatchesBitSize(bit_size, ast, ast.LongDoubleTy))
849 return GetType(ast.LongDoubleTy);
850 if (QualTypeMatchesBitSize(bit_size, ast, ast.HalfTy))
851 return GetType(ast.HalfTy);
852 break;
853
854 case eEncodingVector:
855 // Sanity check that bit_size is a multiple of 8's.
856 if (bit_size && !(bit_size & 0x7u))
857 return GetType(ast.getExtVectorType(ast.UnsignedCharTy, bit_size / 8));
858 break;
859 }
860
861 return CompilerType();
862}
863
864lldb::BasicType
865TypeSystemClang::GetBasicTypeEnumeration(ConstString name) {
866 if (name) {
867 typedef UniqueCStringMap<lldb::BasicType> TypeNameToBasicTypeMap;
868 static TypeNameToBasicTypeMap g_type_map;
869 static llvm::once_flag g_once_flag;
870 llvm::call_once(g_once_flag, []() {
871 // "void"
872 g_type_map.Append(ConstString("void"), eBasicTypeVoid);
873
874 // "char"
875 g_type_map.Append(ConstString("char"), eBasicTypeChar);
876 g_type_map.Append(ConstString("signed char"), eBasicTypeSignedChar);
877 g_type_map.Append(ConstString("unsigned char"), eBasicTypeUnsignedChar);
878 g_type_map.Append(ConstString("wchar_t"), eBasicTypeWChar);
879 g_type_map.Append(ConstString("signed wchar_t"), eBasicTypeSignedWChar);
880 g_type_map.Append(ConstString("unsigned wchar_t"),
881 eBasicTypeUnsignedWChar);
882 // "short"
883 g_type_map.Append(ConstString("short"), eBasicTypeShort);
884 g_type_map.Append(ConstString("short int"), eBasicTypeShort);
885 g_type_map.Append(ConstString("unsigned short"), eBasicTypeUnsignedShort);
886 g_type_map.Append(ConstString("unsigned short int"),
887 eBasicTypeUnsignedShort);
888
889 // "int"
890 g_type_map.Append(ConstString("int"), eBasicTypeInt);
891 g_type_map.Append(ConstString("signed int"), eBasicTypeInt);
892 g_type_map.Append(ConstString("unsigned int"), eBasicTypeUnsignedInt);
893 g_type_map.Append(ConstString("unsigned"), eBasicTypeUnsignedInt);
894
895 // "long"
896 g_type_map.Append(ConstString("long"), eBasicTypeLong);
897 g_type_map.Append(ConstString("long int"), eBasicTypeLong);
898 g_type_map.Append(ConstString("unsigned long"), eBasicTypeUnsignedLong);
899 g_type_map.Append(ConstString("unsigned long int"),
900 eBasicTypeUnsignedLong);
901
902 // "long long"
903 g_type_map.Append(ConstString("long long"), eBasicTypeLongLong);
904 g_type_map.Append(ConstString("long long int"), eBasicTypeLongLong);
905 g_type_map.Append(ConstString("unsigned long long"),
906 eBasicTypeUnsignedLongLong);
907 g_type_map.Append(ConstString("unsigned long long int"),
908 eBasicTypeUnsignedLongLong);
909
910 // "int128"
911 g_type_map.Append(ConstString("__int128_t"), eBasicTypeInt128);
912 g_type_map.Append(ConstString("__uint128_t"), eBasicTypeUnsignedInt128);
913
914 // Miscellaneous
915 g_type_map.Append(ConstString("bool"), eBasicTypeBool);
916 g_type_map.Append(ConstString("float"), eBasicTypeFloat);
917 g_type_map.Append(ConstString("double"), eBasicTypeDouble);
918 g_type_map.Append(ConstString("long double"), eBasicTypeLongDouble);
919 g_type_map.Append(ConstString("id"), eBasicTypeObjCID);
920 g_type_map.Append(ConstString("SEL"), eBasicTypeObjCSel);
921 g_type_map.Append(ConstString("nullptr"), eBasicTypeNullPtr);
922 g_type_map.Sort();
923 });
924
925 return g_type_map.Find(name, eBasicTypeInvalid);
926 }
927 return eBasicTypeInvalid;
928}
929
930uint32_t TypeSystemClang::GetPointerByteSize() {
931 if (m_pointer_byte_size == 0)
932 if (auto size = GetBasicType(lldb::eBasicTypeVoid)
933 .GetPointerType()
934 .GetByteSize(nullptr))
935 m_pointer_byte_size = *size;
936 return m_pointer_byte_size;
937}
938
939CompilerType TypeSystemClang::GetBasicType(lldb::BasicType basic_type) {
940 clang::ASTContext &ast = getASTContext();
941
942 lldb::opaque_compiler_type_t clang_type =
943 GetOpaqueCompilerType(&ast, basic_type);
944
945 if (clang_type)
946 return CompilerType(this, clang_type);
947 return CompilerType();
948}
949
950CompilerType TypeSystemClang::GetBuiltinTypeForDWARFEncodingAndBitSize(
951 llvm::StringRef type_name, uint32_t dw_ate, uint32_t bit_size) {
952 ASTContext &ast = getASTContext();
953
954 switch (dw_ate) {
955 default:
956 break;
957
958 case DW_ATE_address:
959 if (QualTypeMatchesBitSize(bit_size, ast, ast.VoidPtrTy))
960 return GetType(ast.VoidPtrTy);
961 break;
962
963 case DW_ATE_boolean:
964 if (QualTypeMatchesBitSize(bit_size, ast, ast.BoolTy))
965 return GetType(ast.BoolTy);
966 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy))
967 return GetType(ast.UnsignedCharTy);
968 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy))
969 return GetType(ast.UnsignedShortTy);
970 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedIntTy))
971 return GetType(ast.UnsignedIntTy);
972 break;
973
974 case DW_ATE_lo_user:
975 // This has been seen to mean DW_AT_complex_integer
976 if (type_name.contains("complex")) {
977 CompilerType complex_int_clang_type =
978 GetBuiltinTypeForDWARFEncodingAndBitSize("int", DW_ATE_signed,
979 bit_size / 2);
980 return GetType(
981 ast.getComplexType(ClangUtil::GetQualType(complex_int_clang_type)));
982 }
983 break;
984
985 case DW_ATE_complex_float:
986 if (QualTypeMatchesBitSize(bit_size, ast, ast.FloatComplexTy))
987 return GetType(ast.FloatComplexTy);
988 else if (QualTypeMatchesBitSize(bit_size, ast, ast.DoubleComplexTy))
989 return GetType(ast.DoubleComplexTy);
990 else if (QualTypeMatchesBitSize(bit_size, ast, ast.LongDoubleComplexTy))
991 return GetType(ast.LongDoubleComplexTy);
992 else {
993 CompilerType complex_float_clang_type =
994 GetBuiltinTypeForDWARFEncodingAndBitSize("float", DW_ATE_float,
995 bit_size / 2);
996 return GetType(
997 ast.getComplexType(ClangUtil::GetQualType(complex_float_clang_type)));
998 }
999 break;
1000
1001 case DW_ATE_float:
1002 if (type_name == "float" &&
1003 QualTypeMatchesBitSize(bit_size, ast, ast.FloatTy))
1004 return GetType(ast.FloatTy);
1005 if (type_name == "double" &&
1006 QualTypeMatchesBitSize(bit_size, ast, ast.DoubleTy))
1007 return GetType(ast.DoubleTy);
1008 if (type_name == "long double" &&
1009 QualTypeMatchesBitSize(bit_size, ast, ast.LongDoubleTy))
1010 return GetType(ast.LongDoubleTy);
1011 // Fall back to not requiring a name match
1012 if (QualTypeMatchesBitSize(bit_size, ast, ast.FloatTy))
1013 return GetType(ast.FloatTy);
1014 if (QualTypeMatchesBitSize(bit_size, ast, ast.DoubleTy))
1015 return GetType(ast.DoubleTy);
1016 if (QualTypeMatchesBitSize(bit_size, ast, ast.LongDoubleTy))
1017 return GetType(ast.LongDoubleTy);
1018 if (QualTypeMatchesBitSize(bit_size, ast, ast.HalfTy))
1019 return GetType(ast.HalfTy);
1020 break;
1021
1022 case DW_ATE_signed:
1023 if (!type_name.empty()) {
1024 if (type_name == "wchar_t" &&
1025 QualTypeMatchesBitSize(bit_size, ast, ast.WCharTy) &&
1026 (getTargetInfo() &&
1027 TargetInfo::isTypeSigned(getTargetInfo()->getWCharType())))
1028 return GetType(ast.WCharTy);
1029 if (type_name == "void" &&
1030 QualTypeMatchesBitSize(bit_size, ast, ast.VoidTy))
1031 return GetType(ast.VoidTy);
1032 if (type_name.contains("long long") &&
1033 QualTypeMatchesBitSize(bit_size, ast, ast.LongLongTy))
1034 return GetType(ast.LongLongTy);
1035 if (type_name.contains("long") &&
1036 QualTypeMatchesBitSize(bit_size, ast, ast.LongTy))
1037 return GetType(ast.LongTy);
1038 if (type_name.contains("short") &&
1039 QualTypeMatchesBitSize(bit_size, ast, ast.ShortTy))
1040 return GetType(ast.ShortTy);
1041 if (type_name.contains("char")) {
1042 if (QualTypeMatchesBitSize(bit_size, ast, ast.CharTy))
1043 return GetType(ast.CharTy);
1044 if (QualTypeMatchesBitSize(bit_size, ast, ast.SignedCharTy))
1045 return GetType(ast.SignedCharTy);
1046 }
1047 if (type_name.contains("int")) {
1048 if (QualTypeMatchesBitSize(bit_size, ast, ast.IntTy))
1049 return GetType(ast.IntTy);
1050 if (QualTypeMatchesBitSize(bit_size, ast, ast.Int128Ty))
1051 return GetType(ast.Int128Ty);
1052 }
1053 }
1054 // We weren't able to match up a type name, just search by size
1055 if (QualTypeMatchesBitSize(bit_size, ast, ast.CharTy))
1056 return GetType(ast.CharTy);
1057 if (QualTypeMatchesBitSize(bit_size, ast, ast.ShortTy))
1058 return GetType(ast.ShortTy);
1059 if (QualTypeMatchesBitSize(bit_size, ast, ast.IntTy))
1060 return GetType(ast.IntTy);
1061 if (QualTypeMatchesBitSize(bit_size, ast, ast.LongTy))
1062 return GetType(ast.LongTy);
1063 if (QualTypeMatchesBitSize(bit_size, ast, ast.LongLongTy))
1064 return GetType(ast.LongLongTy);
1065 if (QualTypeMatchesBitSize(bit_size, ast, ast.Int128Ty))
1066 return GetType(ast.Int128Ty);
1067 break;
1068
1069 case DW_ATE_signed_char:
1070 if (ast.getLangOpts().CharIsSigned && type_name == "char") {
1071 if (QualTypeMatchesBitSize(bit_size, ast, ast.CharTy))
1072 return GetType(ast.CharTy);
1073 }
1074 if (QualTypeMatchesBitSize(bit_size, ast, ast.SignedCharTy))
1075 return GetType(ast.SignedCharTy);
1076 break;
1077
1078 case DW_ATE_unsigned:
1079 if (!type_name.empty()) {
1080 if (type_name == "wchar_t") {
1081 if (QualTypeMatchesBitSize(bit_size, ast, ast.WCharTy)) {
1082 if (!(getTargetInfo() &&
1083 TargetInfo::isTypeSigned(getTargetInfo()->getWCharType())))
1084 return GetType(ast.WCharTy);
1085 }
1086 }
1087 if (type_name.contains("long long")) {
1088 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongLongTy))
1089 return GetType(ast.UnsignedLongLongTy);
1090 } else if (type_name.contains("long")) {
1091 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongTy))
1092 return GetType(ast.UnsignedLongTy);
1093 } else if (type_name.contains("short")) {
1094 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy))
1095 return GetType(ast.UnsignedShortTy);
1096 } else if (type_name.contains("char")) {
1097 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy))
1098 return GetType(ast.UnsignedCharTy);
1099 } else if (type_name.contains("int")) {
1100 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedIntTy))
1101 return GetType(ast.UnsignedIntTy);
1102 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedInt128Ty))
1103 return GetType(ast.UnsignedInt128Ty);
1104 }
1105 }
1106 // We weren't able to match up a type name, just search by size
1107 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy))
1108 return GetType(ast.UnsignedCharTy);
1109 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy))
1110 return GetType(ast.UnsignedShortTy);
1111 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedIntTy))
1112 return GetType(ast.UnsignedIntTy);
1113 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongTy))
1114 return GetType(ast.UnsignedLongTy);
1115 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongLongTy))
1116 return GetType(ast.UnsignedLongLongTy);
1117 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedInt128Ty))
1118 return GetType(ast.UnsignedInt128Ty);
1119 break;
1120
1121 case DW_ATE_unsigned_char:
1122 if (!ast.getLangOpts().CharIsSigned && type_name == "char") {
1123 if (QualTypeMatchesBitSize(bit_size, ast, ast.CharTy))
1124 return GetType(ast.CharTy);
1125 }
1126 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy))
1127 return GetType(ast.UnsignedCharTy);
1128 if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy))
1129 return GetType(ast.UnsignedShortTy);
1130 break;
1131
1132 case DW_ATE_imaginary_float:
1133 break;
1134
1135 case DW_ATE_UTF:
1136 switch (bit_size) {
1137 case 8:
1138 return GetType(ast.Char8Ty);
1139 case 16:
1140 return GetType(ast.Char16Ty);
1141 case 32:
1142 return GetType(ast.Char32Ty);
1143 default:
1144 if (!type_name.empty()) {
1145 if (type_name == "char16_t")
1146 return GetType(ast.Char16Ty);
1147 if (type_name == "char32_t")
1148 return GetType(ast.Char32Ty);
1149 if (type_name == "char8_t")
1150 return GetType(ast.Char8Ty);
1151 }
1152 }
1153 break;
1154 }
1155 // This assert should fire for anything that we don't catch above so we know
1156 // to fix any issues we run into.
1157 if (!type_name.empty()) {
1158 std::string type_name_str = type_name.str();
1159 Host::SystemLog(Host::eSystemLogError,
1160 "error: need to add support for DW_TAG_base_type '%s' "
1161 "encoded with DW_ATE = 0x%x, bit_size = %u\n",
1162 type_name_str.c_str(), dw_ate, bit_size);
1163 } else {
1164 Host::SystemLog(Host::eSystemLogError, "error: need to add support for "
1165 "DW_TAG_base_type encoded with "
1166 "DW_ATE = 0x%x, bit_size = %u\n",
1167 dw_ate, bit_size);
1168 }
1169 return CompilerType();
1170}
1171
1172CompilerType TypeSystemClang::GetCStringType(bool is_const) {
1173 ASTContext &ast = getASTContext();
1174 QualType char_type(ast.CharTy);
1175
1176 if (is_const)
1177 char_type.addConst();
1178
1179 return GetType(ast.getPointerType(char_type));
1180}
1181
1182bool TypeSystemClang::AreTypesSame(CompilerType type1, CompilerType type2,
1183 bool ignore_qualifiers) {
1184 TypeSystemClang *ast =
1185 llvm::dyn_cast_or_null<TypeSystemClang>(type1.GetTypeSystem());
1186 if (!ast || ast != type2.GetTypeSystem())
1187 return false;
1188
1189 if (type1.GetOpaqueQualType() == type2.GetOpaqueQualType())
1190 return true;
1191
1192 QualType type1_qual = ClangUtil::GetQualType(type1);
1193 QualType type2_qual = ClangUtil::GetQualType(type2);
1194
1195 if (ignore_qualifiers) {
1196 type1_qual = type1_qual.getUnqualifiedType();
1197 type2_qual = type2_qual.getUnqualifiedType();
1198 }
1199
1200 return ast->getASTContext().hasSameType(type1_qual, type2_qual);
1201}
1202
1203CompilerType TypeSystemClang::GetTypeForDecl(void *opaque_decl) {
1204 if (!opaque_decl)
1205 return CompilerType();
1206
1207 clang::Decl *decl = static_cast<clang::Decl *>(opaque_decl);
1208 if (auto *named_decl = llvm::dyn_cast<clang::NamedDecl>(decl))
1209 return GetTypeForDecl(named_decl);
1210 return CompilerType();
1211}
1212
1213CompilerDeclContext TypeSystemClang::CreateDeclContext(DeclContext *ctx) {
1214 // Check that the DeclContext actually belongs to this ASTContext.
1215 assert(&ctx->getParentASTContext() == &getASTContext());
1216 return CompilerDeclContext(this, ctx);
1217}
1218
1219CompilerType TypeSystemClang::GetTypeForDecl(clang::NamedDecl *decl) {
1220 if (clang::ObjCInterfaceDecl *interface_decl =
1221 llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl))
1222 return GetTypeForDecl(interface_decl);
1223 if (clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(decl))
1224 return GetTypeForDecl(tag_decl);
1225 return CompilerType();
1226}
1227
1228CompilerType TypeSystemClang::GetTypeForDecl(TagDecl *decl) {
1229 return GetType(getASTContext().getTagDeclType(decl));
1230}
1231
1232CompilerType TypeSystemClang::GetTypeForDecl(ObjCInterfaceDecl *decl) {
1233 return GetType(getASTContext().getObjCInterfaceType(decl));
1234}
1235
1236#pragma mark Structure, Unions, Classes
1237
1238void TypeSystemClang::SetOwningModule(clang::Decl *decl,
1239 OptionalClangModuleID owning_module) {
1240 if (!decl || !owning_module.HasValue())
1241 return;
1242
1243 decl->setFromASTFile();
1244 decl->setOwningModuleID(owning_module.GetValue());
1245 decl->setModuleOwnershipKind(clang::Decl::ModuleOwnershipKind::Visible);
1246}
1247
1248OptionalClangModuleID
1249TypeSystemClang::GetOrCreateClangModule(llvm::StringRef name,
1250 OptionalClangModuleID parent,
1251 bool is_framework, bool is_explicit) {
1252 // Get the external AST source which holds the modules.
1253 auto *ast_source = llvm::dyn_cast_or_null<ClangExternalASTSourceCallbacks>(
1254 getASTContext().getExternalSource());
1255 assert(ast_source && "external ast source was lost");
1256 if (!ast_source)
1257 return {};
1258
1259 // Lazily initialize the module map.
1260 if (!m_header_search_up) {
1261 auto HSOpts = std::make_shared<clang::HeaderSearchOptions>();
1262 m_header_search_up = std::make_unique<clang::HeaderSearch>(
1263 HSOpts, *m_source_manager_up, *m_diagnostics_engine_up,
1264 *m_language_options_up, m_target_info_up.get());
1265 m_module_map_up = std::make_unique<clang::ModuleMap>(
1266 *m_source_manager_up, *m_diagnostics_engine_up, *m_language_options_up,
1267 m_target_info_up.get(), *m_header_search_up);
1268 }
1269
1270 // Get or create the module context.
1271 bool created;
1272 clang::Module *module;
1273 auto parent_desc = ast_source->getSourceDescriptor(parent.GetValue());
1274 std::tie(module, created) = m_module_map_up->findOrCreateModule(
1275 name, parent_desc ? parent_desc->getModuleOrNull() : nullptr,
1276 is_framework, is_explicit);
1277 if (!created)
1278 return ast_source->GetIDForModule(module);
1279
1280 return ast_source->RegisterModule(module);
1281}
1282
1283CompilerType TypeSystemClang::CreateRecordType(
1284 clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
1285 AccessType access_type, llvm::StringRef name, int kind,
1286 LanguageType language, ClangASTMetadata *metadata, bool exports_symbols) {
1287 ASTContext &ast = getASTContext();
1288
1289 if (decl_ctx == nullptr)
1290 decl_ctx = ast.getTranslationUnitDecl();
1291
1292 if (language == eLanguageTypeObjC ||
1293 language == eLanguageTypeObjC_plus_plus) {
1294 bool isForwardDecl = true;
1295 bool isInternal = false;
1296 return CreateObjCClass(name, decl_ctx, owning_module, isForwardDecl,
1297 isInternal, metadata);
1298 }
1299
1300 // NOTE: Eventually CXXRecordDecl will be merged back into RecordDecl and
1301 // we will need to update this code. I was told to currently always use the
1302 // CXXRecordDecl class since we often don't know from debug information if
1303 // something is struct or a class, so we default to always use the more
1304 // complete definition just in case.
1305
1306 bool has_name = !name.empty();
1307 CXXRecordDecl *decl = CXXRecordDecl::CreateDeserialized(ast, 0);
1308 decl->setTagKind(static_cast<TagDecl::TagKind>(kind));
1309 decl->setDeclContext(decl_ctx);
1310 if (has_name)
1311 decl->setDeclName(&ast.Idents.get(name));
1312 SetOwningModule(decl, owning_module);
1313
1314 if (!has_name) {
1315 // In C++ a lambda is also represented as an unnamed class. This is
1316 // different from an *anonymous class* that the user wrote:
1317 //
1318 // struct A {
1319 // // anonymous class (GNU/MSVC extension)
1320 // struct {
1321 // int x;
1322 // };
1323 // // unnamed class within a class
1324 // struct {
1325 // int y;
1326 // } B;
1327 // };
1328 //
1329 // void f() {
1330 // // unammed class outside of a class
1331 // struct {
1332 // int z;
1333 // } C;
1334 // }
1335 //
1336 // Anonymous classes is a GNU/MSVC extension that clang supports. It
1337 // requires the anonymous class be embedded within a class. So the new
1338 // heuristic verifies this condition.
1339 if (isa<CXXRecordDecl>(decl_ctx) && exports_symbols)
1340 decl->setAnonymousStructOrUnion(true);
1341 }
1342
1343 if (decl) {
1344 if (metadata)
1345 SetMetadata(decl, *metadata);
1346
1347 if (access_type != eAccessNone)
1348 decl->setAccess(ConvertAccessTypeToAccessSpecifier(access_type));
1349
1350 if (decl_ctx)
1351 decl_ctx->addDecl(decl);
1352
1353 return GetType(ast.getTagDeclType(decl));
1354 }
1355 return CompilerType();
1356}
1357
1358namespace {
1359 bool IsValueParam(const clang::TemplateArgument &argument) {
1360 return argument.getKind() == TemplateArgument::Integral;
1361 }
1362}
1363
1364static TemplateParameterList *CreateTemplateParameterList(
1365 ASTContext &ast,
1366 const TypeSystemClang::TemplateParameterInfos &template_param_infos,
1367 llvm::SmallVector<NamedDecl *, 8> &template_param_decls) {
1368 const bool parameter_pack = false;
1369 const bool is_typename = false;
1370 const unsigned depth = 0;
1371 const size_t num_template_params = template_param_infos.args.size();
1372 DeclContext *const decl_context =
1373 ast.getTranslationUnitDecl(); // Is this the right decl context?,
1374 for (size_t i = 0; i < num_template_params; ++i) {
1375 const char *name = template_param_infos.names[i];
1376
1377 IdentifierInfo *identifier_info = nullptr;
1378 if (name && name[0])
1379 identifier_info = &ast.Idents.get(name);
1380 if (IsValueParam(template_param_infos.args[i])) {
1381 QualType template_param_type =
1382 template_param_infos.args[i].getIntegralType();
1383 template_param_decls.push_back(NonTypeTemplateParmDecl::Create(
1384 ast, decl_context, SourceLocation(), SourceLocation(), depth, i,
1385 identifier_info, template_param_type, parameter_pack,
1386 ast.getTrivialTypeSourceInfo(template_param_type)));
1387 } else {
1388 template_param_decls.push_back(TemplateTypeParmDecl::Create(
1389 ast, decl_context, SourceLocation(), SourceLocation(), depth, i,
1390 identifier_info, is_typename, parameter_pack));
1391 }
1392 }
1393
1394 if (template_param_infos.packed_args) {
1395 IdentifierInfo *identifier_info = nullptr;
1396 if (template_param_infos.pack_name && template_param_infos.pack_name[0])
1397 identifier_info = &ast.Idents.get(template_param_infos.pack_name);
1398 const bool parameter_pack_true = true;
1399
1400 if (!template_param_infos.packed_args->args.empty() &&
1401 IsValueParam(template_param_infos.packed_args->args[0])) {
1402 QualType template_param_type =
1403 template_param_infos.packed_args->args[0].getIntegralType();
1404 template_param_decls.push_back(NonTypeTemplateParmDecl::Create(
1405 ast, decl_context, SourceLocation(), SourceLocation(), depth,
1406 num_template_params, identifier_info, template_param_type,
1407 parameter_pack_true,
1408 ast.getTrivialTypeSourceInfo(template_param_type)));
1409 } else {
1410 template_param_decls.push_back(TemplateTypeParmDecl::Create(
1411 ast, decl_context, SourceLocation(), SourceLocation(), depth,
1412 num_template_params, identifier_info, is_typename,
1413 parameter_pack_true));
1414 }
1415 }
1416 clang::Expr *const requires_clause = nullptr; // TODO: Concepts
1417 TemplateParameterList *template_param_list = TemplateParameterList::Create(
1418 ast, SourceLocation(), SourceLocation(), template_param_decls,
1419 SourceLocation(), requires_clause);
1420 return template_param_list;
1421}
1422
1423clang::FunctionTemplateDecl *TypeSystemClang::CreateFunctionTemplateDecl(
1424 clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
1425 clang::FunctionDecl *func_decl,
1426 const TemplateParameterInfos &template_param_infos) {
1427 // /// Create a function template node.
1428 ASTContext &ast = getASTContext();
1429
1430 llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1431 TemplateParameterList *template_param_list = CreateTemplateParameterList(
1432 ast, template_param_infos, template_param_decls);
1433 FunctionTemplateDecl *func_tmpl_decl =
1434 FunctionTemplateDecl::CreateDeserialized(ast, 0);
1435 func_tmpl_decl->setDeclContext(decl_ctx);
1436 func_tmpl_decl->setLocation(func_decl->getLocation());
1437 func_tmpl_decl->setDeclName(func_decl->getDeclName());
1438 func_tmpl_decl->init(func_decl, template_param_list);
1439 SetOwningModule(func_tmpl_decl, owning_module);
1440
1441 for (size_t i = 0, template_param_decl_count = template_param_decls.size();
1442 i < template_param_decl_count; ++i) {
1443 // TODO: verify which decl context we should put template_param_decls into..
1444 template_param_decls[i]->setDeclContext(func_decl);
1445 }
1446 // Function templates inside a record need to have an access specifier.
1447 // It doesn't matter what access specifier we give the template as LLDB
1448 // anyway allows accessing everything inside a record.
1449 if (decl_ctx->isRecord())
1450 func_tmpl_decl->setAccess(clang::AccessSpecifier::AS_public);
1451
1452 return func_tmpl_decl;
1453}
1454
1455void TypeSystemClang::CreateFunctionTemplateSpecializationInfo(
1456 FunctionDecl *func_decl, clang::FunctionTemplateDecl *func_tmpl_decl,
1457 const TemplateParameterInfos &infos) {
1458 TemplateArgumentList *template_args_ptr =
1459 TemplateArgumentList::CreateCopy(func_decl->getASTContext(), infos.args);
1460
1461 func_decl->setFunctionTemplateSpecialization(func_tmpl_decl,
1462 template_args_ptr, nullptr);
1463}
1464
1465ClassTemplateDecl *TypeSystemClang::CreateClassTemplateDecl(
1466 DeclContext *decl_ctx, OptionalClangModuleID owning_module,
1467 lldb::AccessType access_type, const char *class_name, int kind,
1468 const TemplateParameterInfos &template_param_infos) {
1469 ASTContext &ast = getASTContext();
1470
1471 ClassTemplateDecl *class_template_decl = nullptr;
1472 if (decl_ctx == nullptr)
1473 decl_ctx = ast.getTranslationUnitDecl();
1474
1475 IdentifierInfo &identifier_info = ast.Idents.get(class_name);
1476 DeclarationName decl_name(&identifier_info);
1477
1478 clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name);
1479
1480 for (NamedDecl *decl : result) {
1481 class_template_decl = dyn_cast<clang::ClassTemplateDecl>(decl);
1482 if (class_template_decl)
1483 return class_template_decl;
1484 }
1485
1486 llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1487
1488 TemplateParameterList *template_param_list = CreateTemplateParameterList(
1489 ast, template_param_infos, template_param_decls);
1490
1491 CXXRecordDecl *template_cxx_decl = CXXRecordDecl::CreateDeserialized(ast, 0);
1492 template_cxx_decl->setTagKind(static_cast<TagDecl::TagKind>(kind));
1493 // What decl context do we use here? TU? The actual decl context?
1494 template_cxx_decl->setDeclContext(decl_ctx);
1495 template_cxx_decl->setDeclName(decl_name);
1496 SetOwningModule(template_cxx_decl, owning_module);
1497
1498 for (size_t i = 0, template_param_decl_count = template_param_decls.size();
1499 i < template_param_decl_count; ++i) {
1500 template_param_decls[i]->setDeclContext(template_cxx_decl);
1501 }
1502
1503 // With templated classes, we say that a class is templated with
1504 // specializations, but that the bare class has no functions.
1505 // template_cxx_decl->startDefinition();
1506 // template_cxx_decl->completeDefinition();
1507
1508 class_template_decl = ClassTemplateDecl::CreateDeserialized(ast, 0);
1509 // What decl context do we use here? TU? The actual decl context?
1510 class_template_decl->setDeclContext(decl_ctx);
1511 class_template_decl->setDeclName(decl_name);
1512 class_template_decl->init(template_cxx_decl, template_param_list);
1513 template_cxx_decl->setDescribedClassTemplate(class_template_decl);
1514 SetOwningModule(class_template_decl, owning_module);
1515
1516 if (class_template_decl) {
1517 if (access_type != eAccessNone)
1518 class_template_decl->setAccess(
1519 ConvertAccessTypeToAccessSpecifier(access_type));
1520
1521 decl_ctx->addDecl(class_template_decl);
1522
1523 VerifyDecl(class_template_decl);
1524 }
1525
1526 return class_template_decl;
1527}
1528
1529TemplateTemplateParmDecl *
1530TypeSystemClang::CreateTemplateTemplateParmDecl(const char *template_name) {
1531 ASTContext &ast = getASTContext();
1532
1533 auto *decl_ctx = ast.getTranslationUnitDecl();
1534
1535 IdentifierInfo &identifier_info = ast.Idents.get(template_name);
1536 llvm::SmallVector<NamedDecl *, 8> template_param_decls;
1537
1538 TypeSystemClang::TemplateParameterInfos template_param_infos;
1539 TemplateParameterList *template_param_list = CreateTemplateParameterList(
1540 ast, template_param_infos, template_param_decls);
1541
1542 // LLDB needs to create those decls only to be able to display a
1543 // type that includes a template template argument. Only the name matters for
1544 // this purpose, so we use dummy values for the other characteristics of the
1545 // type.
1546 return TemplateTemplateParmDecl::Create(
1547 ast, decl_ctx, SourceLocation(),
1548 /*Depth*/ 0, /*Position*/ 0,
1549 /*IsParameterPack*/ false, &identifier_info, template_param_list);
1550}
1551
1552ClassTemplateSpecializationDecl *
1553TypeSystemClang::CreateClassTemplateSpecializationDecl(
1554 DeclContext *decl_ctx, OptionalClangModuleID owning_module,
1555 ClassTemplateDecl *class_template_decl, int kind,
1556 const TemplateParameterInfos &template_param_infos) {
1557 ASTContext &ast = getASTContext();
1558 llvm::SmallVector<clang::TemplateArgument, 2> args(
1559 template_param_infos.args.size() +
1560 (template_param_infos.packed_args ? 1 : 0));
1561 std::copy(template_param_infos.args.begin(), template_param_infos.args.end(),
1562 args.begin());
1563 if (template_param_infos.packed_args) {
1564 args[args.size() - 1] = TemplateArgument::CreatePackCopy(
1565 ast, template_param_infos.packed_args->args);
1566 }
1567 ClassTemplateSpecializationDecl *class_template_specialization_decl =
1568 ClassTemplateSpecializationDecl::CreateDeserialized(ast, 0);
1569 class_template_specialization_decl->setTagKind(
1570 static_cast<TagDecl::TagKind>(kind));
1571 class_template_specialization_decl->setDeclContext(decl_ctx);
1572 class_template_specialization_decl->setInstantiationOf(class_template_decl);
1573 class_template_specialization_decl->setTemplateArgs(
1574 TemplateArgumentList::CreateCopy(ast, args));
1575 ast.getTypeDeclType(class_template_specialization_decl, nullptr);
1576 class_template_specialization_decl->setDeclName(
1577 class_template_decl->getDeclName());
1578 SetOwningModule(class_template_specialization_decl, owning_module);
1579 decl_ctx->addDecl(class_template_specialization_decl);
1580
1581 class_template_specialization_decl->setSpecializationKind(
1582 TSK_ExplicitSpecialization);
1583
1584 return class_template_specialization_decl;
1585}
1586
1587CompilerType TypeSystemClang::CreateClassTemplateSpecializationType(
1588 ClassTemplateSpecializationDecl *class_template_specialization_decl) {
1589 if (class_template_specialization_decl) {
1590 ASTContext &ast = getASTContext();
1591 return GetType(ast.getTagDeclType(class_template_specialization_decl));
1592 }
1593 return CompilerType();
1594}
1595
1596static inline bool check_op_param(bool is_method,
1597 clang::OverloadedOperatorKind op_kind,
1598 bool unary, bool binary,
1599 uint32_t num_params) {
1600 // Special-case call since it can take any number of operands
1601 if (op_kind == OO_Call)
1602 return true;
1603
1604 // The parameter count doesn't include "this"
1605 if (is_method)
1606 ++num_params;
1607 if (num_params == 1)
1608 return unary;
1609 if (num_params == 2)
1610 return binary;
1611 else
1612 return false;
1613}
1614
1615bool TypeSystemClang::CheckOverloadedOperatorKindParameterCount(
1616 bool is_method, clang::OverloadedOperatorKind op_kind,
1617 uint32_t num_params) {
1618 switch (op_kind) {
1619 default:
1620 break;
1621 // C++ standard allows any number of arguments to new/delete
1622 case OO_New:
1623 case OO_Array_New:
1624 case OO_Delete:
1625 case OO_Array_Delete:
1626 return true;
1627 }
1628
1629#define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \
1630 case OO_##Name: \
1631 return check_op_param(is_method, op_kind, Unary, Binary, num_params);
1632 switch (op_kind) {
1633#include "clang/Basic/OperatorKinds.def"
1634 default:
1635 break;
1636 }
1637 return false;
1638}
1639
1640clang::AccessSpecifier
1641TypeSystemClang::UnifyAccessSpecifiers(clang::AccessSpecifier lhs,
1642 clang::AccessSpecifier rhs) {
1643 // Make the access equal to the stricter of the field and the nested field's
1644 // access
1645 if (lhs == AS_none || rhs == AS_none)
1646 return AS_none;
1647 if (lhs == AS_private || rhs == AS_private)
1648 return AS_private;
1649 if (lhs == AS_protected || rhs == AS_protected)
1650 return AS_protected;
1651 return AS_public;
1652}
1653
1654bool TypeSystemClang::FieldIsBitfield(FieldDecl *field,
1655 uint32_t &bitfield_bit_size) {
1656 ASTContext &ast = getASTContext();
1657 if (field == nullptr)
1658 return false;
1659
1660 if (field->isBitField()) {
1661 Expr *bit_width_expr = field->getBitWidth();
1662 if (bit_width_expr) {
1663 if (Optional<llvm::APSInt> bit_width_apsint =
1664 bit_width_expr->getIntegerConstantExpr(ast)) {
1665 bitfield_bit_size = bit_width_apsint->getLimitedValue(UINT32_MAX);
1666 return true;
1667 }
1668 }
1669 }
1670 return false;
1671}
1672
1673bool TypeSystemClang::RecordHasFields(const RecordDecl *record_decl) {
1674 if (record_decl == nullptr)
1675 return false;
1676
1677 if (!record_decl->field_empty())
1678 return true;
1679
1680 // No fields, lets check this is a CXX record and check the base classes
1681 const CXXRecordDecl *cxx_record_decl = dyn_cast<CXXRecordDecl>(record_decl);
1682 if (cxx_record_decl) {
1683 CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1684 for (base_class = cxx_record_decl->bases_begin(),
1685 base_class_end = cxx_record_decl->bases_end();
1686 base_class != base_class_end; ++base_class) {
1687 const CXXRecordDecl *base_class_decl = cast<CXXRecordDecl>(
1688 base_class->getType()->getAs<RecordType>()->getDecl());
1689 if (RecordHasFields(base_class_decl))
1690 return true;
1691 }
1692 }
1693 return false;
1694}
1695
1696#pragma mark Objective-C Classes
1697
1698CompilerType TypeSystemClang::CreateObjCClass(
1699 llvm::StringRef name, clang::DeclContext *decl_ctx,
1700 OptionalClangModuleID owning_module, bool isForwardDecl, bool isInternal,
1701 ClangASTMetadata *metadata) {
1702 ASTContext &ast = getASTContext();
1703 assert(!name.empty());
1704 if (!decl_ctx)
1705 decl_ctx = ast.getTranslationUnitDecl();
1706
1707 ObjCInterfaceDecl *decl = ObjCInterfaceDecl::CreateDeserialized(ast, 0);
1708 decl->setDeclContext(decl_ctx);
1709 decl->setDeclName(&ast.Idents.get(name));
1710 /*isForwardDecl,*/
1711 decl->setImplicit(isInternal);
1712 SetOwningModule(decl, owning_module);
1713
1714 if (decl && metadata)
1715 SetMetadata(decl, *metadata);
1716
1717 return GetType(ast.getObjCInterfaceType(decl));
1718}
1719
1720static inline bool BaseSpecifierIsEmpty(const CXXBaseSpecifier *b) {
1721 return !TypeSystemClang::RecordHasFields(b->getType()->getAsCXXRecordDecl());
1722}
1723
1724uint32_t
1725TypeSystemClang::GetNumBaseClasses(const CXXRecordDecl *cxx_record_decl,
1726 bool omit_empty_base_classes) {
1727 uint32_t num_bases = 0;
1728 if (cxx_record_decl) {
1729 if (omit_empty_base_classes) {
1730 CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
1731 for (base_class = cxx_record_decl->bases_begin(),
1732 base_class_end = cxx_record_decl->bases_end();
1733 base_class != base_class_end; ++base_class) {
1734 // Skip empty base classes
1735 if (BaseSpecifierIsEmpty(base_class))
1736 continue;
1737 ++num_bases;
1738 }
1739 } else
1740 num_bases = cxx_record_decl->getNumBases();
1741 }
1742 return num_bases;
1743}
1744
1745#pragma mark Namespace Declarations
1746
1747NamespaceDecl *TypeSystemClang::GetUniqueNamespaceDeclaration(
1748 const char *name, clang::DeclContext *decl_ctx,
1749 OptionalClangModuleID owning_module, bool is_inline) {
1750 NamespaceDecl *namespace_decl = nullptr;
1751 ASTContext &ast = getASTContext();
1752 TranslationUnitDecl *translation_unit_decl = ast.getTranslationUnitDecl();
1753 if (!decl_ctx)
1754 decl_ctx = translation_unit_decl;
1755
1756 if (name) {
1757 IdentifierInfo &identifier_info = ast.Idents.get(name);
1758 DeclarationName decl_name(&identifier_info);
1759 clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name);
1760 for (NamedDecl *decl : result) {
1761 namespace_decl = dyn_cast<clang::NamespaceDecl>(decl);
1762 if (namespace_decl)
1763 return namespace_decl;
1764 }
1765
1766 namespace_decl =
1767 NamespaceDecl::Create(ast, decl_ctx, is_inline, SourceLocation(),
1768 SourceLocation(), &identifier_info, nullptr);
1769
1770 decl_ctx->addDecl(namespace_decl);
1771 } else {
1772 if (decl_ctx == translation_unit_decl) {
1773 namespace_decl = translation_unit_decl->getAnonymousNamespace();
1774 if (namespace_decl)
1775 return namespace_decl;
1776
1777 namespace_decl =
1778 NamespaceDecl::Create(ast, decl_ctx, false, SourceLocation(),
1779 SourceLocation(), nullptr, nullptr);
1780 translation_unit_decl->setAnonymousNamespace(namespace_decl);
1781 translation_unit_decl->addDecl(namespace_decl);
1782 assert(namespace_decl == translation_unit_decl->getAnonymousNamespace());
1783 } else {
1784 NamespaceDecl *parent_namespace_decl = cast<NamespaceDecl>(decl_ctx);
1785 if (parent_namespace_decl) {
1786 namespace_decl = parent_namespace_decl->getAnonymousNamespace();
1787 if (namespace_decl)
1788 return namespace_decl;
1789 namespace_decl =
1790 NamespaceDecl::Create(ast, decl_ctx, false, SourceLocation(),
1791 SourceLocation(), nullptr, nullptr);
1792 parent_namespace_decl->setAnonymousNamespace(namespace_decl);
1793 parent_namespace_decl->addDecl(namespace_decl);
1794 assert(namespace_decl ==
1795 parent_namespace_decl->getAnonymousNamespace());
1796 } else {
1797 assert(false && "GetUniqueNamespaceDeclaration called with no name and "
1798 "no namespace as decl_ctx");
1799 }
1800 }
1801 }
1802 // Note: namespaces can span multiple modules, so perhaps this isn't a good
1803 // idea.
1804 SetOwningModule(namespace_decl, owning_module);
1805
1806 VerifyDecl(namespace_decl);
1807 return namespace_decl;
1808}
1809
1810clang::BlockDecl *
1811TypeSystemClang::CreateBlockDeclaration(clang::DeclContext *ctx,
1812 OptionalClangModuleID owning_module) {
1813 if (ctx) {
1814 clang::BlockDecl *decl =
1815 clang::BlockDecl::CreateDeserialized(getASTContext(), 0);
1816 decl->setDeclContext(ctx);
1817 ctx->addDecl(decl);
1818 SetOwningModule(decl, owning_module);
1819 return decl;
1820 }
1821 return nullptr;
1822}
1823
1824clang::DeclContext *FindLCABetweenDecls(clang::DeclContext *left,
1825 clang::DeclContext *right,
1826 clang::DeclContext *root) {
1827 if (root == nullptr)
1828 return nullptr;
1829
1830 std::set<clang::DeclContext *> path_left;
1831 for (clang::DeclContext *d = left; d != nullptr; d = d->getParent())
1832 path_left.insert(d);
1833
1834 for (clang::DeclContext *d = right; d != nullptr; d = d->getParent())
1835 if (path_left.find(d) != path_left.end())
1836 return d;
1837
1838 return nullptr;
1839}
1840
1841clang::UsingDirectiveDecl *TypeSystemClang::CreateUsingDirectiveDeclaration(
1842 clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
1843 clang::NamespaceDecl *ns_decl) {
1844 if (decl_ctx && ns_decl) {
1845 auto *translation_unit = getASTContext().getTranslationUnitDecl();
1846 clang::UsingDirectiveDecl *using_decl = clang::UsingDirectiveDecl::Create(
1847 getASTContext(), decl_ctx, clang::SourceLocation(),
1848 clang::SourceLocation(), clang::NestedNameSpecifierLoc(),
1849 clang::SourceLocation(), ns_decl,
1850 FindLCABetweenDecls(decl_ctx, ns_decl,
1851 translation_unit));
1852 decl_ctx->addDecl(using_decl);
1853 SetOwningModule(using_decl, owning_module);
1854 return using_decl;
1855 }
1856 return nullptr;
1857}
1858
1859clang::UsingDecl *
1860TypeSystemClang::CreateUsingDeclaration(clang::DeclContext *current_decl_ctx,
1861 OptionalClangModuleID owning_module,
1862 clang::NamedDecl *target) {
1863 if (current_decl_ctx && target) {
1864 clang::UsingDecl *using_decl = clang::UsingDecl::Create(
1865 getASTContext(), current_decl_ctx, clang::SourceLocation(),
1866 clang::NestedNameSpecifierLoc(), clang::DeclarationNameInfo(), false);
1867 SetOwningModule(using_decl, owning_module);
1868 clang::UsingShadowDecl *shadow_decl = clang::UsingShadowDecl::Create(
1869 getASTContext(), current_decl_ctx, clang::SourceLocation(), using_decl,
1870 target);
1871 SetOwningModule(shadow_decl, owning_module);
1872 using_decl->addShadowDecl(shadow_decl);
1873 current_decl_ctx->addDecl(using_decl);
1874 return using_decl;
1875 }
1876 return nullptr;
1877}
1878
1879clang::VarDecl *TypeSystemClang::CreateVariableDeclaration(
1880 clang::DeclContext *decl_context, OptionalClangModuleID owning_module,
1881 const char *name, clang::QualType type) {
1882 if (decl_context) {
1883 clang::VarDecl *var_decl =
1884 clang::VarDecl::CreateDeserialized(getASTContext(), 0);
1885 var_decl->setDeclContext(decl_context);
1886 if (name && name[0])
1887 var_decl->setDeclName(&getASTContext().Idents.getOwn(name));
1888 var_decl->setType(type);
1889 SetOwningModule(var_decl, owning_module);
1890 var_decl->setAccess(clang::AS_public);
1891 decl_context->addDecl(var_decl);
1892 return var_decl;
1893 }
1894 return nullptr;
1895}
1896
1897lldb::opaque_compiler_type_t
1898TypeSystemClang::GetOpaqueCompilerType(clang::ASTContext *ast,
1899 lldb::BasicType basic_type) {
1900 switch (basic_type) {
1901 case eBasicTypeVoid:
1902 return ast->VoidTy.getAsOpaquePtr();
1903 case eBasicTypeChar:
1904 return ast->CharTy.getAsOpaquePtr();
1905 case eBasicTypeSignedChar:
1906 return ast->SignedCharTy.getAsOpaquePtr();
1907 case eBasicTypeUnsignedChar:
1908 return ast->UnsignedCharTy.getAsOpaquePtr();
1909 case eBasicTypeWChar:
1910 return ast->getWCharType().getAsOpaquePtr();
1911 case eBasicTypeSignedWChar:
1912 return ast->getSignedWCharType().getAsOpaquePtr();
1913 case eBasicTypeUnsignedWChar:
1914 return ast->getUnsignedWCharType().getAsOpaquePtr();
1915 case eBasicTypeChar16:
1916 return ast->Char16Ty.getAsOpaquePtr();
1917 case eBasicTypeChar32:
1918 return ast->Char32Ty.getAsOpaquePtr();
1919 case eBasicTypeShort:
1920 return ast->ShortTy.getAsOpaquePtr();
1921 case eBasicTypeUnsignedShort:
1922 return ast->UnsignedShortTy.getAsOpaquePtr();
1923 case eBasicTypeInt:
1924 return ast->IntTy.getAsOpaquePtr();
1925 case eBasicTypeUnsignedInt:
1926 return ast->UnsignedIntTy.getAsOpaquePtr();
1927 case eBasicTypeLong:
1928 return ast->LongTy.getAsOpaquePtr();
1929 case eBasicTypeUnsignedLong:
1930 return ast->UnsignedLongTy.getAsOpaquePtr();
1931 case eBasicTypeLongLong:
1932 return ast->LongLongTy.getAsOpaquePtr();
1933 case eBasicTypeUnsignedLongLong:
1934 return ast->UnsignedLongLongTy.getAsOpaquePtr();
1935 case eBasicTypeInt128:
1936 return ast->Int128Ty.getAsOpaquePtr();
1937 case eBasicTypeUnsignedInt128:
1938 return ast->UnsignedInt128Ty.getAsOpaquePtr();
1939 case eBasicTypeBool:
1940 return ast->BoolTy.getAsOpaquePtr();
1941 case eBasicTypeHalf:
1942 return ast->HalfTy.getAsOpaquePtr();
1943 case eBasicTypeFloat:
1944 return ast->FloatTy.getAsOpaquePtr();
1945 case eBasicTypeDouble:
1946 return ast->DoubleTy.getAsOpaquePtr();
1947 case eBasicTypeLongDouble:
1948 return ast->LongDoubleTy.getAsOpaquePtr();
1949 case eBasicTypeFloatComplex:
1950 return ast->FloatComplexTy.getAsOpaquePtr();
1951 case eBasicTypeDoubleComplex:
1952 return ast->DoubleComplexTy.getAsOpaquePtr();
1953 case eBasicTypeLongDoubleComplex:
1954 return ast->LongDoubleComplexTy.getAsOpaquePtr();
1955 case eBasicTypeObjCID:
1956 return ast->getObjCIdType().getAsOpaquePtr();
1957 case eBasicTypeObjCClass:
1958 return ast->getObjCClassType().getAsOpaquePtr();
1959 case eBasicTypeObjCSel:
1960 return ast->getObjCSelType().getAsOpaquePtr();
1961 case eBasicTypeNullPtr:
1962 return ast->NullPtrTy.getAsOpaquePtr();
1963 default:
1964 return nullptr;
1965 }
1966}
1967
1968#pragma mark Function Types
1969
1970clang::DeclarationName
1971TypeSystemClang::GetDeclarationName(llvm::StringRef name,
1972 const CompilerType &function_clang_type) {
1973 clang::OverloadedOperatorKind op_kind = clang::NUM_OVERLOADED_OPERATORS;
1974 if (!IsOperator(name, op_kind) || op_kind == clang::NUM_OVERLOADED_OPERATORS)
1975 return DeclarationName(&getASTContext().Idents.get(
1976 name)); // Not operator, but a regular function.
1977
1978 // Check the number of operator parameters. Sometimes we have seen bad DWARF
1979 // that doesn't correctly describe operators and if we try to create a method
1980 // and add it to the class, clang will assert and crash, so we need to make
1981 // sure things are acceptable.
1982 clang::QualType method_qual_type(ClangUtil::GetQualType(function_clang_type));
1983 const clang::FunctionProtoType *function_type =
1984 llvm::dyn_cast<clang::FunctionProtoType>(method_qual_type.getTypePtr());
1985 if (function_type == nullptr)
1986 return clang::DeclarationName();
1987
1988 const bool is_method = false;
1989 const unsigned int num_params = function_type->getNumParams();
1990 if (!TypeSystemClang::CheckOverloadedOperatorKindParameterCount(
1991 is_method, op_kind, num_params))
1992 return clang::DeclarationName();
1993
1994 return getASTContext().DeclarationNames.getCXXOperatorName(op_kind);
1995}
1996
1997PrintingPolicy TypeSystemClang::GetTypePrintingPolicy() {
1998 clang::PrintingPolicy printing_policy(getASTContext().getPrintingPolicy());
1999 printing_policy.SuppressTagKeyword = true;
2000 // Inline namespaces are important for some type formatters (e.g., libc++
2001 // and libstdc++ are differentiated by their inline namespaces).
2002 printing_policy.SuppressInlineNamespace = false;
2003 printing_policy.SuppressUnwrittenScope = false;
2004 // Default arguments are also always important for type formatters. Otherwise
2005 // we would need to always specify two type names for the setups where we do
2006 // know the default arguments and where we don't know default arguments.
2007 //
2008 // For example, without this we would need to have formatters for both:
2009 // std::basic_string<char>
2010 // and
2011 // std::basic_string<char, std::char_traits<char>, std::allocator<char> >
2012 // to support setups where LLDB was able to reconstruct default arguments
2013 // (and we then would have suppressed them from the type name) and also setups
2014 // where LLDB wasn't able to reconstruct the default arguments.
2015 printing_policy.SuppressDefaultTemplateArgs = false;
2016 return printing_policy;
2017}
2018
2019std::string TypeSystemClang::GetTypeNameForDecl(const NamedDecl *named_decl) {
2020 clang::PrintingPolicy printing_policy = GetTypePrintingPolicy();
2021 std::string result;
2022 llvm::raw_string_ostream os(result);
2023 named_decl->printQualifiedName(os, printing_policy);
2024 return result;
2025}
2026
2027FunctionDecl *TypeSystemClang::CreateFunctionDeclaration(
2028 clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
2029 llvm::StringRef name, const CompilerType &function_clang_type,
2030 clang::StorageClass storage, bool is_inline) {
2031 FunctionDecl *func_decl = nullptr;
2032 ASTContext &ast = getASTContext();
2033 if (!decl_ctx)
2034 decl_ctx = ast.getTranslationUnitDecl();
2035
2036 const bool hasWrittenPrototype = true;
2037 const bool isConstexprSpecified = false;
2038
2039 clang::DeclarationName declarationName =
2040 GetDeclarationName(name, function_clang_type);
2041 func_decl = FunctionDecl::CreateDeserialized(ast, 0);
2042 func_decl->setDeclContext(decl_ctx);
2043 func_decl->setDeclName(declarationName);
2044 func_decl->setType(ClangUtil::GetQualType(function_clang_type));
2045 func_decl->setStorageClass(storage);
2046 func_decl->setInlineSpecified(is_inline);
2047 func_decl->setHasWrittenPrototype(hasWrittenPrototype);
2048 func_decl->setConstexprKind(isConstexprSpecified
2049 ? ConstexprSpecKind::Constexpr
2050 : ConstexprSpecKind::Unspecified);
2051 SetOwningModule(func_decl, owning_module);
2052 if (func_decl)
2053 decl_ctx->addDecl(func_decl);
2054
2055 VerifyDecl(func_decl);
2056
2057 return func_decl;
2058}
2059
2060CompilerType
2061TypeSystemClang::CreateFunctionType(const CompilerType &result_type,
2062 const CompilerType *args, unsigned num_args,
2063 bool is_variadic, unsigned type_quals,
2064 clang::CallingConv cc) {
2065 if (!result_type || !ClangUtil::IsClangType(result_type))
2066 return CompilerType(); // invalid return type
2067
2068 std::vector<QualType> qual_type_args;
2069 if (num_args > 0 && args == nullptr)
2070 return CompilerType(); // invalid argument array passed in
2071
2072 // Verify that all arguments are valid and the right type
2073 for (unsigned i = 0; i < num_args; ++i) {
2074 if (args[i]) {
2075 // Make sure we have a clang type in args[i] and not a type from another
2076 // language whose name might match
2077 const bool is_clang_type = ClangUtil::IsClangType(args[i]);
2078 lldbassert(is_clang_type);
2079 if (is_clang_type)
2080 qual_type_args.push_back(ClangUtil::GetQualType(args[i]));
2081 else
2082 return CompilerType(); // invalid argument type (must be a clang type)
2083 } else
2084 return CompilerType(); // invalid argument type (empty)
2085 }
2086
2087 // TODO: Detect calling convention in DWARF?
2088 FunctionProtoType::ExtProtoInfo proto_info;
2089 proto_info.ExtInfo = cc;
2090 proto_info.Variadic = is_variadic;
2091 proto_info.ExceptionSpec = EST_None;
2092 proto_info.TypeQuals = clang::Qualifiers::fromFastMask(type_quals);
2093 proto_info.RefQualifier = RQ_None;
2094
2095 return GetType(getASTContext().getFunctionType(
2096 ClangUtil::GetQualType(result_type), qual_type_args, proto_info));
2097}
2098
2099ParmVarDecl *TypeSystemClang::CreateParameterDeclaration(
2100 clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
2101 const char *name, const CompilerType &param_type, int storage,
2102 bool add_decl) {
2103 ASTContext &ast = getASTContext();
2104 auto *decl = ParmVarDecl::CreateDeserialized(ast, 0);
2105 decl->setDeclContext(decl_ctx);
2106 if (name && name[0])
2107 decl->setDeclName(&ast.Idents.get(name));
2108 decl->setType(ClangUtil::GetQualType(param_type));
2109 decl->setStorageClass(static_cast<clang::StorageClass>(storage));
2110 SetOwningModule(decl, owning_module);
2111 if (add_decl)
2112 decl_ctx->addDecl(decl);
2113
2114 return decl;
2115}
2116
2117void TypeSystemClang::SetFunctionParameters(FunctionDecl *function_decl,
2118 ParmVarDecl **params,
2119 unsigned num_params) {
2120 if (function_decl)
2121 function_decl->setParams(ArrayRef<ParmVarDecl *>(params, num_params));
2122}
2123
2124CompilerType
2125TypeSystemClang::CreateBlockPointerType(const CompilerType &function_type) {
2126 QualType block_type = m_ast_up->getBlockPointerType(
2127 clang::QualType::getFromOpaquePtr(function_type.GetOpaqueQualType()));
2128
2129 return GetType(block_type);
2130}
2131
2132#pragma mark Array Types
2133
2134CompilerType TypeSystemClang::CreateArrayType(const CompilerType &element_type,
2135 size_t element_count,
2136 bool is_vector) {
2137 if (element_type.IsValid()) {
2138 ASTContext &ast = getASTContext();
2139
2140 if (is_vector) {
2141 return GetType(ast.getExtVectorType(ClangUtil::GetQualType(element_type),
2142 element_count));
2143 } else {
2144
2145 llvm::APInt ap_element_count(64, element_count);
2146 if (element_count == 0) {
2147 return GetType(ast.getIncompleteArrayType(
2148 ClangUtil::GetQualType(element_type), clang::ArrayType::Normal, 0));
2149 } else {
2150 return GetType(ast.getConstantArrayType(
2151 ClangUtil::GetQualType(element_type), ap_element_count, nullptr,
2152 clang::ArrayType::Normal, 0));
2153 }
2154 }
2155 }
2156 return CompilerType();
2157}
2158
2159CompilerType TypeSystemClang::CreateStructForIdentifier(
2160 ConstString type_name,
2161 const std::initializer_list<std::pair<const char *, CompilerType>>
2162 &type_fields,
2163 bool packed) {
2164 CompilerType type;
2165 if (!type_name.IsEmpty() &&
2166 (type = GetTypeForIdentifier<clang::CXXRecordDecl>(type_name))
2167 .IsValid()) {
2168 lldbassert(0 && "Trying to create a type for an existing name");
2169 return type;
2170 }
2171
2172 type = CreateRecordType(nullptr, OptionalClangModuleID(), lldb::eAccessPublic,
2173 type_name.GetCString(), clang::TTK_Struct,
2174 lldb::eLanguageTypeC);
2175 StartTagDeclarationDefinition(type);
2176 for (const auto &field : type_fields)
2177 AddFieldToRecordType(type, field.first, field.second, lldb::eAccessPublic,
2178 0);
2179 if (packed)
2180 SetIsPacked(type);
2181 CompleteTagDeclarationDefinition(type);
2182 return type;
2183}
2184
2185CompilerType TypeSystemClang::GetOrCreateStructForIdentifier(
2186 ConstString type_name,
2187 const std::initializer_list<std::pair<const char *, CompilerType>>
2188 &type_fields,
2189 bool packed) {
2190 CompilerType type;
2191 if ((type = GetTypeForIdentifier<clang::CXXRecordDecl>(type_name)).IsValid())
2192 return type;
2193
2194 return CreateStructForIdentifier(type_name, type_fields, packed);
2195}
2196
2197#pragma mark Enumeration Types
2198
2199CompilerType TypeSystemClang::CreateEnumerationType(
2200 const char *name, clang::DeclContext *decl_ctx,
2201 OptionalClangModuleID owning_module, const Declaration &decl,
2202 const CompilerType &integer_clang_type, bool is_scoped) {
2203 // TODO: Do something intelligent with the Declaration object passed in
2204 // like maybe filling in the SourceLocation with it...
2205 ASTContext &ast = getASTContext();
2206
2207 // TODO: ask about these...
2208 // const bool IsFixed = false;
2209 EnumDecl *enum_decl = EnumDecl::CreateDeserialized(ast, 0);
2210 enum_decl->setDeclContext(decl_ctx);
2211 if (name && name[0])
2212 enum_decl->setDeclName(&ast.Idents.get(name));
2213 enum_decl->setScoped(is_scoped);
2214 enum_decl->setScopedUsingClassTag(is_scoped);
2215 enum_decl->setFixed(false);
2216 SetOwningModule(enum_decl, owning_module);
2217 if (enum_decl) {
2218 if (decl_ctx)
2219 decl_ctx->addDecl(enum_decl);
2220
2221 // TODO: check if we should be setting the promotion type too?
2222 enum_decl->setIntegerType(ClangUtil::GetQualType(integer_clang_type));
2223
2224 enum_decl->setAccess(AS_public); // TODO respect what's in the debug info
2225
2226 return GetType(ast.getTagDeclType(enum_decl));
2227 }
2228 return CompilerType();
2229}
2230
2231CompilerType TypeSystemClang::GetIntTypeFromBitSize(size_t bit_size,
2232 bool is_signed) {
2233 clang::ASTContext &ast = getASTContext();
2234
2235 if (is_signed) {
2236 if (bit_size == ast.getTypeSize(ast.SignedCharTy))
2237 return GetType(ast.SignedCharTy);
2238
2239 if (bit_size == ast.getTypeSize(ast.ShortTy))
2240 return GetType(ast.ShortTy);
2241
2242 if (bit_size == ast.getTypeSize(ast.IntTy))
2243 return GetType(ast.IntTy);
2244
2245 if (bit_size == ast.getTypeSize(ast.LongTy))
2246 return GetType(ast.LongTy);
2247
2248 if (bit_size == ast.getTypeSize(ast.LongLongTy))
2249 return GetType(ast.LongLongTy);
2250
2251 if (bit_size == ast.getTypeSize(ast.Int128Ty))
2252 return GetType(ast.Int128Ty);
2253 } else {
2254 if (bit_size == ast.getTypeSize(ast.UnsignedCharTy))
2255 return GetType(ast.UnsignedCharTy);
2256
2257 if (bit_size == ast.getTypeSize(ast.UnsignedShortTy))
2258 return GetType(ast.UnsignedShortTy);
2259
2260 if (bit_size == ast.getTypeSize(ast.UnsignedIntTy))
2261 return GetType(ast.UnsignedIntTy);
2262
2263 if (bit_size == ast.getTypeSize(ast.UnsignedLongTy))
2264 return GetType(ast.UnsignedLongTy);
2265
2266 if (bit_size == ast.getTypeSize(ast.UnsignedLongLongTy))
2267 return GetType(ast.UnsignedLongLongTy);
2268
2269 if (bit_size == ast.getTypeSize(ast.UnsignedInt128Ty))
2270 return GetType(ast.UnsignedInt128Ty);
2271 }
2272 return CompilerType();
2273}
2274
2275CompilerType TypeSystemClang::GetPointerSizedIntType(bool is_signed) {
2276 return GetIntTypeFromBitSize(
2277 getASTContext().getTypeSize(getASTContext().VoidPtrTy), is_signed);
2278}
2279
2280void TypeSystemClang::DumpDeclContextHiearchy(clang::DeclContext *decl_ctx) {
2281 if (decl_ctx) {
2282 DumpDeclContextHiearchy(decl_ctx->getParent());
2283
2284 clang::NamedDecl *named_decl = llvm::dyn_cast<clang::NamedDecl>(decl_ctx);
2285 if (named_decl) {
2286 printf("%20s: %s\n", decl_ctx->getDeclKindName(),
2287 named_decl->getDeclName().getAsString().c_str());
2288 } else {
2289 printf("%20s\n", decl_ctx->getDeclKindName());
2290 }
2291 }
2292}
2293
2294void TypeSystemClang::DumpDeclHiearchy(clang::Decl *decl) {
2295 if (decl == nullptr)
2296 return;
2297 DumpDeclContextHiearchy(decl->getDeclContext());
2298
2299 clang::RecordDecl *record_decl = llvm::dyn_cast<clang::RecordDecl>(decl);
2300 if (record_decl) {
2301 printf("%20s: %s%s\n", decl->getDeclKindName(),
2302 record_decl->getDeclName().getAsString().c_str(),
2303 record_decl->isInjectedClassName() ? " (injected class name)" : "");
2304
2305 } else {
2306 clang::NamedDecl *named_decl = llvm::dyn_cast<clang::NamedDecl>(decl);
2307 if (named_decl) {
2308 printf("%20s: %s\n", decl->getDeclKindName(),
2309 named_decl->getDeclName().getAsString().c_str());
2310 } else {
2311 printf("%20s\n", decl->getDeclKindName());
2312 }
2313 }
2314}
2315
2316bool TypeSystemClang::DeclsAreEquivalent(clang::Decl *lhs_decl,
2317 clang::Decl *rhs_decl) {
2318 if (lhs_decl && rhs_decl) {
2319 // Make sure the decl kinds match first
2320 const clang::Decl::Kind lhs_decl_kind = lhs_decl->getKind();
2321 const clang::Decl::Kind rhs_decl_kind = rhs_decl->getKind();
2322
2323 if (lhs_decl_kind == rhs_decl_kind) {
2324 // Now check that the decl contexts kinds are all equivalent before we
2325 // have to check any names of the decl contexts...
2326 clang::DeclContext *lhs_decl_ctx = lhs_decl->getDeclContext();
2327 clang::DeclContext *rhs_decl_ctx = rhs_decl->getDeclContext();
2328 if (lhs_decl_ctx && rhs_decl_ctx) {
2329 while (true) {
2330 if (lhs_decl_ctx && rhs_decl_ctx) {
2331 const clang::Decl::Kind lhs_decl_ctx_kind =
2332 lhs_decl_ctx->getDeclKind();
2333 const clang::Decl::Kind rhs_decl_ctx_kind =
2334 rhs_decl_ctx->getDeclKind();
2335 if (lhs_decl_ctx_kind == rhs_decl_ctx_kind) {
2336 lhs_decl_ctx = lhs_decl_ctx->getParent();
2337 rhs_decl_ctx = rhs_decl_ctx->getParent();
2338
2339 if (lhs_decl_ctx == nullptr && rhs_decl_ctx == nullptr)
2340 break;
2341 } else
2342 return false;
2343 } else
2344 return false;
2345 }
2346
2347 // Now make sure the name of the decls match
2348 clang::NamedDecl *lhs_named_decl =
2349 llvm::dyn_cast<clang::NamedDecl>(lhs_decl);
2350 clang::NamedDecl *rhs_named_decl =
2351 llvm::dyn_cast<clang::NamedDecl>(rhs_decl);
2352 if (lhs_named_decl && rhs_named_decl) {
2353 clang::DeclarationName lhs_decl_name = lhs_named_decl->getDeclName();
2354 clang::DeclarationName rhs_decl_name = rhs_named_decl->getDeclName();
2355 if (lhs_decl_name.getNameKind() == rhs_decl_name.getNameKind()) {
2356 if (lhs_decl_name.getAsString() != rhs_decl_name.getAsString())
2357 return false;
2358 } else
2359 return false;
2360 } else
2361 return false;
2362
2363 // We know that the decl context kinds all match, so now we need to
2364 // make sure the names match as well
2365 lhs_decl_ctx = lhs_decl->getDeclContext();
2366 rhs_decl_ctx = rhs_decl->getDeclContext();
2367 while (true) {
2368 switch (lhs_decl_ctx->getDeclKind()) {
2369 case clang::Decl::TranslationUnit:
2370 // We don't care about the translation unit names
2371 return true;
2372 default: {
2373 clang::NamedDecl *lhs_named_decl =
2374 llvm::dyn_cast<clang::NamedDecl>(lhs_decl_ctx);
2375 clang::NamedDecl *rhs_named_decl =
2376 llvm::dyn_cast<clang::NamedDecl>(rhs_decl_ctx);
2377 if (lhs_named_decl && rhs_named_decl) {
2378 clang::DeclarationName lhs_decl_name =
2379 lhs_named_decl->getDeclName();
2380 clang::DeclarationName rhs_decl_name =
2381 rhs_named_decl->getDeclName();
2382 if (lhs_decl_name.getNameKind() == rhs_decl_name.getNameKind()) {
2383 if (lhs_decl_name.getAsString() != rhs_decl_name.getAsString())
2384 return false;
2385 } else
2386 return false;
2387 } else
2388 return false;
2389 } break;
2390 }
2391 lhs_decl_ctx = lhs_decl_ctx->getParent();
2392 rhs_decl_ctx = rhs_decl_ctx->getParent();
2393 }
2394 }
2395 }
2396 }
2397 return false;
2398}
2399bool TypeSystemClang::GetCompleteDecl(clang::ASTContext *ast,
2400 clang::Decl *decl) {
2401 if (!decl)
2402 return false;
2403
2404 ExternalASTSource *ast_source = ast->getExternalSource();
2405
2406 if (!ast_source)
2407 return false;
2408
2409 if (clang::TagDecl *tag_decl = llvm::dyn_cast<clang::TagDecl>(decl)) {
2410 if (tag_decl->isCompleteDefinition())
2411 return true;
2412
2413 if (!tag_decl->hasExternalLexicalStorage())
2414 return false;
2415
2416 ast_source->CompleteType(tag_decl);
2417
2418 return !tag_decl->getTypeForDecl()->isIncompleteType();
2419 } else if (clang::ObjCInterfaceDecl *objc_interface_decl =
2420 llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl)) {
2421 if (objc_interface_decl->getDefinition())
2422 return true;
2423
2424 if (!objc_interface_decl->hasExternalLexicalStorage())
2425 return false;
2426
2427 ast_source->CompleteType(objc_interface_decl);
2428
2429 return !objc_interface_decl->getTypeForDecl()->isIncompleteType();
2430 } else {
2431 return false;
2432 }
2433}
2434
2435void TypeSystemClang::SetMetadataAsUserID(const clang::Decl *decl,
2436 user_id_t user_id) {
2437 ClangASTMetadata meta_data;
2438 meta_data.SetUserID(user_id);
2439 SetMetadata(decl, meta_data);
2440}
2441
2442void TypeSystemClang::SetMetadataAsUserID(const clang::Type *type,
2443 user_id_t user_id) {
2444 ClangASTMetadata meta_data;
2445 meta_data.SetUserID(user_id);
2446 SetMetadata(type, meta_data);
2447}
2448
2449void TypeSystemClang::SetMetadata(const clang::Decl *object,
2450 ClangASTMetadata &metadata) {
2451 m_decl_metadata[object] = metadata;
2452}
2453
2454void TypeSystemClang::SetMetadata(const clang::Type *object,
2455 ClangASTMetadata &metadata) {
2456 m_type_metadata[object] = metadata;
2457}
2458
2459ClangASTMetadata *TypeSystemClang::GetMetadata(const clang::Decl *object) {
2460 auto It = m_decl_metadata.find(object);
2461 if (It != m_decl_metadata.end())
2462 return &It->second;
2463 return nullptr;
2464}
2465
2466ClangASTMetadata *TypeSystemClang::GetMetadata(const clang::Type *object) {
2467 auto It = m_type_metadata.find(object);
2468 if (It != m_type_metadata.end())
2469 return &It->second;
2470 return nullptr;
2471}
2472
2473bool TypeSystemClang::SetTagTypeKind(clang::QualType tag_qual_type,
2474 int kind) const {
2475 const clang::Type *clang_type = tag_qual_type.getTypePtr();
2476 if (clang_type) {
2477 const clang::TagType *tag_type = llvm::dyn_cast<clang::TagType>(clang_type);
2478 if (tag_type) {
2479 clang::TagDecl *tag_decl =
2480 llvm::dyn_cast<clang::TagDecl>(tag_type->getDecl());
2481 if (tag_decl) {
2482 tag_decl->setTagKind((clang::TagDecl::TagKind)kind);
2483 return true;
2484 }
2485 }
2486 }
2487 return false;
2488}
2489
2490bool TypeSystemClang::SetDefaultAccessForRecordFields(
2491 clang::RecordDecl *record_decl, int default_accessibility,
2492 int *assigned_accessibilities, size_t num_assigned_accessibilities) {
2493 if (record_decl) {
2494 uint32_t field_idx;
2495 clang::RecordDecl::field_iterator field, field_end;
2496 for (field = record_decl->field_begin(),
2497 field_end = record_decl->field_end(), field_idx = 0;
2498 field != field_end; ++field, ++field_idx) {
2499 // If no accessibility was assigned, assign the correct one
2500 if (field_idx < num_assigned_accessibilities &&
2501 assigned_accessibilities[field_idx] == clang::AS_none)
2502 field->setAccess((clang::AccessSpecifier)default_accessibility);
2503 }
2504 return true;
2505 }
2506 return false;
2507}
2508
2509clang::DeclContext *
2510TypeSystemClang::GetDeclContextForType(const CompilerType &type) {
2511 return GetDeclContextForType(ClangUtil::GetQualType(type));
2512}
2513
2514/// Aggressively desugar the provided type, skipping past various kinds of
2515/// syntactic sugar and other constructs one typically wants to ignore.
2516/// The \p mask argument allows one to skip certain kinds of simplifications,
2517/// when one wishes to handle a certain kind of type directly.
2518static QualType
2519RemoveWrappingTypes(QualType type, ArrayRef<clang::Type::TypeClass> mask = {}) {
2520 while (true) {
2521 if (find(mask, type->getTypeClass()) != mask.end())
2522 return type;
2523 switch (type->getTypeClass()) {
2524 // This is not fully correct as _Atomic is more than sugar, but it is
2525 // sufficient for the purposes we care about.
2526 case clang::Type::Atomic:
2527 type = cast<clang::AtomicType>(type)->getValueType();
2528 break;
2529 case clang::Type::Auto:
2530 case clang::Type::Decltype:
2531 case clang::Type::Elaborated:
2532 case clang::Type::Paren:
2533 case clang::Type::SubstTemplateTypeParm:
2534 case clang::Type::TemplateSpecialization:
2535 case clang::Type::Typedef:
2536 case clang::Type::TypeOf:
2537 case clang::Type::TypeOfExpr:
2538 type = type->getLocallyUnqualifiedSingleStepDesugaredType();
2539 break;
2540 default:
2541 return type;
2542 }
2543 }
2544}
2545
2546clang::DeclContext *
2547TypeSystemClang::GetDeclContextForType(clang::QualType type) {
2548 if (type.isNull())
2549 return nullptr;
2550
2551 clang::QualType qual_type = RemoveWrappingTypes(type.getCanonicalType());
2552 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2553 switch (type_class) {
2554 case clang::Type::ObjCInterface:
2555 return llvm::cast<clang::ObjCObjectType>(qual_type.getTypePtr())
2556 ->getInterface();
2557 case clang::Type::ObjCObjectPointer:
2558 return GetDeclContextForType(
2559 llvm::cast<clang::ObjCObjectPointerType>(qual_type.getTypePtr())
2560 ->getPointeeType());
2561 case clang::Type::Record:
2562 return llvm::cast<clang::RecordType>(qual_type)->getDecl();
2563 case clang::Type::Enum:
2564 return llvm::cast<clang::EnumType>(qual_type)->getDecl();
2565 default:
2566 break;
2567 }
2568 // No DeclContext in this type...
2569 return nullptr;
2570}
2571
2572static bool GetCompleteQualType(clang::ASTContext *ast,
2573 clang::QualType qual_type,
2574 bool allow_completion = true) {
2575 qual_type = RemoveWrappingTypes(qual_type);
2576 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2577 switch (type_class) {
2578 case clang::Type::ConstantArray:
2579 case clang::Type::IncompleteArray:
2580 case clang::Type::VariableArray: {
2581 const clang::ArrayType *array_type =
2582 llvm::dyn_cast<clang::ArrayType>(qual_type.getTypePtr());
2583
2584 if (array_type)
2585 return GetCompleteQualType(ast, array_type->getElementType(),
2586 allow_completion);
2587 } break;
2588 case clang::Type::Record: {
2589 clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
2590 if (cxx_record_decl) {
2591 if (cxx_record_decl->hasExternalLexicalStorage()) {
2592 const bool is_complete = cxx_record_decl->isCompleteDefinition();
2593 const bool fields_loaded =
2594 cxx_record_decl->hasLoadedFieldsFromExternalStorage();
2595 if (is_complete && fields_loaded)
2596 return true;
2597
2598 if (!allow_completion)
2599 return false;
2600
2601 // Call the field_begin() accessor to for it to use the external source
2602 // to load the fields...
2603 clang::ExternalASTSource *external_ast_source =
2604 ast->getExternalSource();
2605 if (external_ast_source) {
2606 external_ast_source->CompleteType(cxx_record_decl);
2607 if (cxx_record_decl->isCompleteDefinition()) {
2608 cxx_record_decl->field_begin();
2609 cxx_record_decl->setHasLoadedFieldsFromExternalStorage(true);
2610 }
2611 }
2612 }
2613 }
2614 const clang::TagType *tag_type =
2615 llvm::cast<clang::TagType>(qual_type.getTypePtr());
2616 return !tag_type->isIncompleteType();
2617 } break;
2618
2619 case clang::Type::Enum: {
2620 const clang::TagType *tag_type =
2621 llvm::dyn_cast<clang::TagType>(qual_type.getTypePtr());
2622 if (tag_type) {
2623 clang::TagDecl *tag_decl = tag_type->getDecl();
2624 if (tag_decl) {
2625 if (tag_decl->getDefinition())
2626 return true;
2627
2628 if (!allow_completion)
2629 return false;
2630
2631 if (tag_decl->hasExternalLexicalStorage()) {
2632 if (ast) {
2633 clang::ExternalASTSource *external_ast_source =
2634 ast->getExternalSource();
2635 if (external_ast_source) {
2636 external_ast_source->CompleteType(tag_decl);
2637 return !tag_type->isIncompleteType();
2638 }
2639 }
2640 }
2641 return false;
2642 }
2643 }
2644
2645 } break;
2646 case clang::Type::ObjCObject:
2647 case clang::Type::ObjCInterface: {
2648 const clang::ObjCObjectType *objc_class_type =
2649 llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
2650 if (objc_class_type) {
2651 clang::ObjCInterfaceDecl *class_interface_decl =
2652 objc_class_type->getInterface();
2653 // We currently can't complete objective C types through the newly added
2654 // ASTContext because it only supports TagDecl objects right now...
2655 if (class_interface_decl) {
2656 if (class_interface_decl->getDefinition())
2657 return true;
2658
2659 if (!allow_completion)
2660 return false;
2661
2662 if (class_interface_decl->hasExternalLexicalStorage()) {
2663 if (ast) {
2664 clang::ExternalASTSource *external_ast_source =
2665 ast->getExternalSource();
2666 if (external_ast_source) {
2667 external_ast_source->CompleteType(class_interface_decl);
2668 return !objc_class_type->isIncompleteType();
2669 }
2670 }
2671 }
2672 return false;
2673 }
2674 }
2675 } break;
2676
2677 case clang::Type::Attributed:
2678 return GetCompleteQualType(
2679 ast, llvm::cast<clang::AttributedType>(qual_type)->getModifiedType(),
2680 allow_completion);
2681
2682 default:
2683 break;
2684 }
2685
2686 return true;
2687}
2688
2689static clang::ObjCIvarDecl::AccessControl
2690ConvertAccessTypeToObjCIvarAccessControl(AccessType access) {
2691 switch (access) {
2692 case eAccessNone:
2693 return clang::ObjCIvarDecl::None;
2694 case eAccessPublic:
2695 return clang::ObjCIvarDecl::Public;
2696 case eAccessPrivate:
2697 return clang::ObjCIvarDecl::Private;
2698 case eAccessProtected:
2699 return clang::ObjCIvarDecl::Protected;
2700 case eAccessPackage:
2701 return clang::ObjCIvarDecl::Package;
2702 }
2703 return clang::ObjCIvarDecl::None;
2704}
2705
2706// Tests
2707
2708#ifndef NDEBUG
2709bool TypeSystemClang::Verify(lldb::opaque_compiler_type_t type) {
2710 return !type || llvm::isa<clang::Type>(GetQualType(type).getTypePtr());
2711}
2712#endif
2713
2714bool TypeSystemClang::IsAggregateType(lldb::opaque_compiler_type_t type) {
2715 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
2716
2717 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2718 switch (type_class) {
2719 case clang::Type::IncompleteArray:
2720 case clang::Type::VariableArray:
2721 case clang::Type::ConstantArray:
2722 case clang::Type::ExtVector:
2723 case clang::Type::Vector:
2724 case clang::Type::Record:
2725 case clang::Type::ObjCObject:
2726 case clang::Type::ObjCInterface:
2727 return true;
2728 default:
2729 break;
2730 }
2731 // The clang type does have a value
2732 return false;
2733}
2734
2735bool TypeSystemClang::IsAnonymousType(lldb::opaque_compiler_type_t type) {
2736 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
2737
2738 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2739 switch (type_class) {
2740 case clang::Type::Record: {
2741 if (const clang::RecordType *record_type =
2742 llvm::dyn_cast_or_null<clang::RecordType>(
2743 qual_type.getTypePtrOrNull())) {
2744 if (const clang::RecordDecl *record_decl = record_type->getDecl()) {
2745 return record_decl->isAnonymousStructOrUnion();
2746 }
2747 }
2748 break;
2749 }
2750 default:
2751 break;
2752 }
2753 // The clang type does have a value
2754 return false;
2755}
2756
2757bool TypeSystemClang::IsArrayType(lldb::opaque_compiler_type_t type,
2758 CompilerType *element_type_ptr,
2759 uint64_t *size, bool *is_incomplete) {
2760 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
2761
2762 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2763 switch (type_class) {
2764 default:
2765 break;
2766
2767 case clang::Type::ConstantArray:
2768 if (element_type_ptr)
2769 element_type_ptr->SetCompilerType(
2770 this, llvm::cast<clang::ConstantArrayType>(qual_type)
2771 ->getElementType()
2772 .getAsOpaquePtr());
2773 if (size)
2774 *size = llvm::cast<clang::ConstantArrayType>(qual_type)
2775 ->getSize()
2776 .getLimitedValue(ULLONG_MAX);
2777 if (is_incomplete)
2778 *is_incomplete = false;
2779 return true;
2780
2781 case clang::Type::IncompleteArray:
2782 if (element_type_ptr)
2783 element_type_ptr->SetCompilerType(
2784 this, llvm::cast<clang::IncompleteArrayType>(qual_type)
2785 ->getElementType()
2786 .getAsOpaquePtr());
2787 if (size)
2788 *size = 0;
2789 if (is_incomplete)
2790 *is_incomplete = true;
2791 return true;
2792
2793 case clang::Type::VariableArray:
2794 if (element_type_ptr)
2795 element_type_ptr->SetCompilerType(
2796 this, llvm::cast<clang::VariableArrayType>(qual_type)
2797 ->getElementType()
2798 .getAsOpaquePtr());
2799 if (size)
2800 *size = 0;
2801 if (is_incomplete)
2802 *is_incomplete = false;
2803 return true;
2804
2805 case clang::Type::DependentSizedArray:
2806 if (element_type_ptr)
2807 element_type_ptr->SetCompilerType(
2808 this, llvm::cast<clang::DependentSizedArrayType>(qual_type)
2809 ->getElementType()
2810 .getAsOpaquePtr());
2811 if (size)
2812 *size = 0;
2813 if (is_incomplete)
2814 *is_incomplete = false;
2815 return true;
2816 }
2817 if (element_type_ptr)
2818 element_type_ptr->Clear();
2819 if (size)
2820 *size = 0;
2821 if (is_incomplete)
2822 *is_incomplete = false;
2823 return false;
2824}
2825
2826bool TypeSystemClang::IsVectorType(lldb::opaque_compiler_type_t type,
2827 CompilerType *element_type, uint64_t *size) {
2828 clang::QualType qual_type(GetCanonicalQualType(type));
2829
2830 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2831 switch (type_class) {
2832 case clang::Type::Vector: {
2833 const clang::VectorType *vector_type =
2834 qual_type->getAs<clang::VectorType>();
2835 if (vector_type) {
2836 if (size)
2837 *size = vector_type->getNumElements();
2838 if (element_type)
2839 *element_type = GetType(vector_type->getElementType());
2840 }
2841 return true;
2842 } break;
2843 case clang::Type::ExtVector: {
2844 const clang::ExtVectorType *ext_vector_type =
2845 qual_type->getAs<clang::ExtVectorType>();
2846 if (ext_vector_type) {
2847 if (size)
2848 *size = ext_vector_type->getNumElements();
2849 if (element_type)
2850 *element_type =
2851 CompilerType(this, ext_vector_type->getElementType().getAsOpaquePtr());
2852 }
2853 return true;
2854 }
2855 default:
2856 break;
2857 }
2858 return false;
2859}
2860
2861bool TypeSystemClang::IsRuntimeGeneratedType(
2862 lldb::opaque_compiler_type_t type) {
2863 clang::DeclContext *decl_ctx = GetDeclContextForType(GetQualType(type));
2864 if (!decl_ctx)
2865 return false;
2866
2867 if (!llvm::isa<clang::ObjCInterfaceDecl>(decl_ctx))
2868 return false;
2869
2870 clang::ObjCInterfaceDecl *result_iface_decl =
2871 llvm::dyn_cast<clang::ObjCInterfaceDecl>(decl_ctx);
2872
2873 ClangASTMetadata *ast_metadata = GetMetadata(result_iface_decl);
2874 if (!ast_metadata)
2875 return false;
2876 return (ast_metadata->GetISAPtr() != 0);
2877}
2878
2879bool TypeSystemClang::IsCharType(lldb::opaque_compiler_type_t type) {
2880 return GetQualType(type).getUnqualifiedType()->isCharType();
2881}
2882
2883bool TypeSystemClang::IsCompleteType(lldb::opaque_compiler_type_t type) {
2884 const bool allow_completion = false;
2885 return GetCompleteQualType(&getASTContext(), GetQualType(type),
2886 allow_completion);
2887}
2888
2889bool TypeSystemClang::IsConst(lldb::opaque_compiler_type_t type) {
2890 return GetQualType(type).isConstQualified();
2891}
2892
2893bool TypeSystemClang::IsCStringType(lldb::opaque_compiler_type_t type,
2894 uint32_t &length) {
2895 CompilerType pointee_or_element_clang_type;
2896 length = 0;
2897 Flags type_flags(GetTypeInfo(type, &pointee_or_element_clang_type));
2898
2899 if (!pointee_or_element_clang_type.IsValid())
2900 return false;
2901
2902 if (type_flags.AnySet(eTypeIsArray | eTypeIsPointer)) {
2903 if (pointee_or_element_clang_type.IsCharType()) {
2904 if (type_flags.Test(eTypeIsArray)) {
2905 // We know the size of the array and it could be a C string since it is
2906 // an array of characters
2907 length = llvm::cast<clang::ConstantArrayType>(
2908 GetCanonicalQualType(type).getTypePtr())
2909 ->getSize()
2910 .getLimitedValue();
2911 }
2912 return true;
2913 }
2914 }
2915 return false;
2916}
2917
2918bool TypeSystemClang::IsFunctionType(lldb::opaque_compiler_type_t type) {
2919 if (type) {
2920 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
2921
2922 if (qual_type->isFunctionType()) {
2923 return true;
2924 }
2925
2926 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2927 switch (type_class) {
2928 default:
2929 break;
2930 case clang::Type::LValueReference:
2931 case clang::Type::RValueReference: {
2932 const clang::ReferenceType *reference_type =
2933 llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
2934 if (reference_type)
2935 return IsFunctionType(
2936 reference_type->getPointeeType().getAsOpaquePtr());
2937 } break;
2938 }
2939 }
2940 return false;
2941}
2942
2943// Used to detect "Homogeneous Floating-point Aggregates"
2944uint32_t
2945TypeSystemClang::IsHomogeneousAggregate(lldb::opaque_compiler_type_t type,
2946 CompilerType *base_type_ptr) {
2947 if (!type)
2948 return 0;
2949
2950 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
2951 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
2952 switch (type_class) {
2953 case clang::Type::Record:
2954 if (GetCompleteType(type)) {
2955 const clang::CXXRecordDecl *cxx_record_decl =
2956 qual_type->getAsCXXRecordDecl();
2957 if (cxx_record_decl) {
2958 if (cxx_record_decl->getNumBases() || cxx_record_decl->isDynamicClass())
2959 return 0;
2960 }
2961 const clang::RecordType *record_type =
2962 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
2963 if (record_type) {
2964 const clang::RecordDecl *record_decl = record_type->getDecl();
2965 if (record_decl) {
2966 // We are looking for a structure that contains only floating point
2967 // types
2968 clang::RecordDecl::field_iterator field_pos,
2969 field_end = record_decl->field_end();
2970 uint32_t num_fields = 0;
2971 bool is_hva = false;
2972 bool is_hfa = false;
2973 clang::QualType base_qual_type;
2974 uint64_t base_bitwidth = 0;
2975 for (field_pos = record_decl->field_begin(); field_pos != field_end;
2976 ++field_pos) {
2977 clang::QualType field_qual_type = field_pos->getType();
2978 uint64_t field_bitwidth = getASTContext().getTypeSize(qual_type);
2979 if (field_qual_type->isFloatingType()) {
2980 if (field_qual_type->isComplexType())
2981 return 0;
2982 else {
2983 if (num_fields == 0)
2984 base_qual_type = field_qual_type;
2985 else {
2986 if (is_hva)
2987 return 0;
2988 is_hfa = true;
2989 if (field_qual_type.getTypePtr() !=
2990 base_qual_type.getTypePtr())
2991 return 0;
2992 }
2993 }
2994 } else if (field_qual_type->isVectorType() ||
2995 field_qual_type->isExtVectorType()) {
2996 if (num_fields == 0) {
2997 base_qual_type = field_qual_type;
2998 base_bitwidth = field_bitwidth;
2999 } else {
3000 if (is_hfa)
3001 return 0;
3002 is_hva = true;
3003 if (base_bitwidth != field_bitwidth)
3004 return 0;
3005 if (field_qual_type.getTypePtr() != base_qual_type.getTypePtr())
3006 return 0;
3007 }
3008 } else
3009 return 0;
3010 ++num_fields;
3011 }
3012 if (base_type_ptr)
3013 *base_type_ptr = CompilerType(this, base_qual_type.getAsOpaquePtr());
3014 return num_fields;
3015 }
3016 }
3017 }
3018 break;
3019
3020 default:
3021 break;
3022 }
3023 return 0;
3024}
3025
3026size_t TypeSystemClang::GetNumberOfFunctionArguments(
3027 lldb::opaque_compiler_type_t type) {
3028 if (type) {
3029 clang::QualType qual_type(GetCanonicalQualType(type));
3030 const clang::FunctionProtoType *func =
3031 llvm::dyn_cast<clang::FunctionProtoType>(qual_type.getTypePtr());
3032 if (func)
3033 return func->getNumParams();
3034 }
3035 return 0;
3036}
3037
3038CompilerType
3039TypeSystemClang::GetFunctionArgumentAtIndex(lldb::opaque_compiler_type_t type,
3040 const size_t index) {
3041 if (type) {
3042 clang::QualType qual_type(GetQualType(type));
3043 const clang::FunctionProtoType *func =
3044 llvm::dyn_cast<clang::FunctionProtoType>(qual_type.getTypePtr());
3045 if (func) {
3046 if (index < func->getNumParams())
3047 return CompilerType(this, func->getParamType(index).getAsOpaquePtr());
3048 }
3049 }
3050 return CompilerType();
3051}
3052
3053bool TypeSystemClang::IsFunctionPointerType(lldb::opaque_compiler_type_t type) {
3054 if (type) {
3055 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
3056
3057 if (qual_type->isFunctionPointerType())
3058 return true;
3059
3060 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3061 switch (type_class) {
3062 default:
3063 break;
3064
3065 case clang::Type::LValueReference:
3066 case clang::Type::RValueReference: {
3067 const clang::ReferenceType *reference_type =
3068 llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
3069 if (reference_type)
3070 return IsFunctionPointerType(
3071 reference_type->getPointeeType().getAsOpaquePtr());
3072 } break;
3073 }
3074 }
3075 return false;
3076}
3077
3078bool TypeSystemClang::IsBlockPointerType(
3079 lldb::opaque_compiler_type_t type,
3080 CompilerType *function_pointer_type_ptr) {
3081 if (type) {
3082 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
3083
3084 if (qual_type->isBlockPointerType()) {
3085 if (function_pointer_type_ptr) {
3086 const clang::BlockPointerType *block_pointer_type =
3087 qual_type->getAs<clang::BlockPointerType>();
3088 QualType pointee_type = block_pointer_type->getPointeeType();
3089 QualType function_pointer_type = m_ast_up->getPointerType(pointee_type);
3090 *function_pointer_type_ptr =
3091 CompilerType(this, function_pointer_type.getAsOpaquePtr());
3092 }
3093 return true;
3094 }
3095
3096 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3097 switch (type_class) {
3098 default:
3099 break;
3100
3101 case clang::Type::LValueReference:
3102 case clang::Type::RValueReference: {
3103 const clang::ReferenceType *reference_type =
3104 llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
3105 if (reference_type)
3106 return IsBlockPointerType(
3107 reference_type->getPointeeType().getAsOpaquePtr(),
3108 function_pointer_type_ptr);
3109 } break;
3110 }
3111 }
3112 return false;
3113}
3114
3115bool TypeSystemClang::IsIntegerType(lldb::opaque_compiler_type_t type,
3116 bool &is_signed) {
3117 if (!type)
3118 return false;
3119
3120 clang::QualType qual_type(GetCanonicalQualType(type));
3121 const clang::BuiltinType *builtin_type =
3122 llvm::dyn_cast<clang::BuiltinType>(qual_type->getCanonicalTypeInternal());
3123
3124 if (builtin_type) {
3125 if (builtin_type->isInteger()) {
3126 is_signed = builtin_type->isSignedInteger();
3127 return true;
3128 }
3129 }
3130
3131 return false;
3132}
3133
3134bool TypeSystemClang::IsEnumerationType(lldb::opaque_compiler_type_t type,
3135 bool &is_signed) {
3136 if (type) {
3137 const clang::EnumType *enum_type = llvm::dyn_cast<clang::EnumType>(
3138 GetCanonicalQualType(type)->getCanonicalTypeInternal());
3139
3140 if (enum_type) {
3141 IsIntegerType(enum_type->getDecl()->getIntegerType().getAsOpaquePtr(),
3142 is_signed);
3143 return true;
3144 }
3145 }
3146
3147 return false;
3148}
3149
3150bool TypeSystemClang::IsScopedEnumerationType(
3151 lldb::opaque_compiler_type_t type) {
3152 if (type) {
3153 const clang::EnumType *enum_type = llvm::dyn_cast<clang::EnumType>(
3154 GetCanonicalQualType(type)->getCanonicalTypeInternal());
3155
3156 if (enum_type) {
3157 return enum_type->isScopedEnumeralType();
3158 }
3159 }
3160
3161 return false;
3162}
3163
3164bool TypeSystemClang::IsPointerType(lldb::opaque_compiler_type_t type,
3165 CompilerType *pointee_type) {
3166 if (type) {
3167 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
3168 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3169 switch (type_class) {
3170 case clang::Type::Builtin:
3171 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
3172 default:
3173 break;
3174 case clang::BuiltinType::ObjCId:
3175 case clang::BuiltinType::ObjCClass:
3176 return true;
3177 }
3178 return false;
3179 case clang::Type::ObjCObjectPointer:
3180 if (pointee_type)
3181 pointee_type->SetCompilerType(
3182 this, llvm::cast<clang::ObjCObjectPointerType>(qual_type)
3183 ->getPointeeType()
3184 .getAsOpaquePtr());
3185 return true;
3186 case clang::Type::BlockPointer:
3187 if (pointee_type)
3188 pointee_type->SetCompilerType(
3189 this, llvm::cast<clang::BlockPointerType>(qual_type)
3190 ->getPointeeType()
3191 .getAsOpaquePtr());
3192 return true;
3193 case clang::Type::Pointer:
3194 if (pointee_type)
3195 pointee_type->SetCompilerType(this,
3196 llvm::cast<clang::PointerType>(qual_type)
3197 ->getPointeeType()
3198 .getAsOpaquePtr());
3199 return true;
3200 case clang::Type::MemberPointer:
3201 if (pointee_type)
3202 pointee_type->SetCompilerType(
3203 this, llvm::cast<clang::MemberPointerType>(qual_type)
3204 ->getPointeeType()
3205 .getAsOpaquePtr());
3206 return true;
3207 default:
3208 break;
3209 }
3210 }
3211 if (pointee_type)
3212 pointee_type->Clear();
3213 return false;
3214}
3215
3216bool TypeSystemClang::IsPointerOrReferenceType(
3217 lldb::opaque_compiler_type_t type, CompilerType *pointee_type) {
3218 if (type) {
3219 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
3220 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3221 switch (type_class) {
3222 case clang::Type::Builtin:
3223 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
3224 default:
3225 break;
3226 case clang::BuiltinType::ObjCId:
3227 case clang::BuiltinType::ObjCClass:
3228 return true;
3229 }
3230 return false;
3231 case clang::Type::ObjCObjectPointer:
3232 if (pointee_type)
3233 pointee_type->SetCompilerType(
3234 this, llvm::cast<clang::ObjCObjectPointerType>(qual_type)
3235 ->getPointeeType().getAsOpaquePtr());
3236 return true;
3237 case clang::Type::BlockPointer:
3238 if (pointee_type)
3239 pointee_type->SetCompilerType(
3240 this, llvm::cast<clang::BlockPointerType>(qual_type)
3241 ->getPointeeType()
3242 .getAsOpaquePtr());
3243 return true;
3244 case clang::Type::Pointer:
3245 if (pointee_type)
3246 pointee_type->SetCompilerType(this,
3247 llvm::cast<clang::PointerType>(qual_type)
3248 ->getPointeeType()
3249 .getAsOpaquePtr());
3250 return true;
3251 case clang::Type::MemberPointer:
3252 if (pointee_type)
3253 pointee_type->SetCompilerType(
3254 this, llvm::cast<clang::MemberPointerType>(qual_type)
3255 ->getPointeeType()
3256 .getAsOpaquePtr());
3257 return true;
3258 case clang::Type::LValueReference:
3259 if (pointee_type)
3260 pointee_type->SetCompilerType(
3261 this, llvm::cast<clang::LValueReferenceType>(qual_type)
3262 ->desugar()
3263 .getAsOpaquePtr());
3264 return true;
3265 case clang::Type::RValueReference:
3266 if (pointee_type)
3267 pointee_type->SetCompilerType(
3268 this, llvm::cast<clang::RValueReferenceType>(qual_type)
3269 ->desugar()
3270 .getAsOpaquePtr());
3271 return true;
3272 default:
3273 break;
3274 }
3275 }
3276 if (pointee_type)
3277 pointee_type->Clear();
3278 return false;
3279}
3280
3281bool TypeSystemClang::IsReferenceType(lldb::opaque_compiler_type_t type,
3282 CompilerType *pointee_type,
3283 bool *is_rvalue) {
3284 if (type) {
3285 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
3286 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3287
3288 switch (type_class) {
3289 case clang::Type::LValueReference:
3290 if (pointee_type)
3291 pointee_type->SetCompilerType(
3292 this, llvm::cast<clang::LValueReferenceType>(qual_type)
3293 ->desugar()
3294 .getAsOpaquePtr());
3295 if (is_rvalue)
3296 *is_rvalue = false;
3297 return true;
3298 case clang::Type::RValueReference:
3299 if (pointee_type)
3300 pointee_type->SetCompilerType(
3301 this, llvm::cast<clang::RValueReferenceType>(qual_type)
3302 ->desugar()
3303 .getAsOpaquePtr());
3304 if (is_rvalue)
3305 *is_rvalue = true;
3306 return true;
3307
3308 default:
3309 break;
3310 }
3311 }
3312 if (pointee_type)
3313 pointee_type->Clear();
3314 return false;
3315}
3316
3317bool TypeSystemClang::IsFloatingPointType(lldb::opaque_compiler_type_t type,
3318 uint32_t &count, bool &is_complex) {
3319 if (type) {
3320 clang::QualType qual_type(GetCanonicalQualType(type));
3321
3322 if (const clang::BuiltinType *BT = llvm::dyn_cast<clang::BuiltinType>(
3323 qual_type->getCanonicalTypeInternal())) {
3324 clang::BuiltinType::Kind kind = BT->getKind();
3325 if (kind >= clang::BuiltinType::Float &&
3326 kind <= clang::BuiltinType::LongDouble) {
3327 count = 1;
3328 is_complex = false;
3329 return true;
3330 }
3331 } else if (const clang::ComplexType *CT =
3332 llvm::dyn_cast<clang::ComplexType>(
3333 qual_type->getCanonicalTypeInternal())) {
3334 if (IsFloatingPointType(CT->getElementType().getAsOpaquePtr(), count,
3335 is_complex)) {
3336 count = 2;
3337 is_complex = true;
3338 return true;
3339 }
3340 } else if (const clang::VectorType *VT = llvm::dyn_cast<clang::VectorType>(
3341 qual_type->getCanonicalTypeInternal())) {
3342 if (IsFloatingPointType(VT->getElementType().getAsOpaquePtr(), count,
3343 is_complex)) {
3344 count = VT->getNumElements();
3345 is_complex = false;
3346 return true;
3347 }
3348 }
3349 }
3350 count = 0;
3351 is_complex = false;
3352 return false;
3353}
3354
3355bool TypeSystemClang::IsDefined(lldb::opaque_compiler_type_t type) {
3356 if (!type)
3357 return false;
3358
3359 clang::QualType qual_type(GetQualType(type));
3360 const clang::TagType *tag_type =
3361 llvm::dyn_cast<clang::TagType>(qual_type.getTypePtr());
3362 if (tag_type) {
3363 clang::TagDecl *tag_decl = tag_type->getDecl();
3364 if (tag_decl)
3365 return tag_decl->isCompleteDefinition();
3366 return false;
3367 } else {
3368 const clang::ObjCObjectType *objc_class_type =
3369 llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
3370 if (objc_class_type) {
3371 clang::ObjCInterfaceDecl *class_interface_decl =
3372 objc_class_type->getInterface();
3373 if (class_interface_decl)
3374 return class_interface_decl->getDefinition() != nullptr;
3375 return false;
3376 }
3377 }
3378 return true;
3379}
3380
3381bool TypeSystemClang::IsObjCClassType(const CompilerType &type) {
3382 if (ClangUtil::IsClangType(type)) {
3383 clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
3384
3385 const clang::ObjCObjectPointerType *obj_pointer_type =
3386 llvm::dyn_cast<clang::ObjCObjectPointerType>(qual_type);
3387
3388 if (obj_pointer_type)
3389 return obj_pointer_type->isObjCClassType();
3390 }
3391 return false;
3392}
3393
3394bool TypeSystemClang::IsObjCObjectOrInterfaceType(const CompilerType &type) {
3395 if (ClangUtil::IsClangType(type))
3396 return ClangUtil::GetCanonicalQualType(type)->isObjCObjectOrInterfaceType();
3397 return false;
3398}
3399
3400bool TypeSystemClang::IsClassType(lldb::opaque_compiler_type_t type) {
3401 if (!type)
3402 return false;
3403 clang::QualType qual_type(GetCanonicalQualType(type));
3404 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3405 return (type_class == clang::Type::Record);
3406}
3407
3408bool TypeSystemClang::IsEnumType(lldb::opaque_compiler_type_t type) {
3409 if (!type)
3410 return false;
3411 clang::QualType qual_type(GetCanonicalQualType(type));
3412 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3413 return (type_class == clang::Type::Enum);
3414}
3415
3416bool TypeSystemClang::IsPolymorphicClass(lldb::opaque_compiler_type_t type) {
3417 if (type) {
3418 clang::QualType qual_type(GetCanonicalQualType(type));
3419 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3420 switch (type_class) {
3421 case clang::Type::Record:
3422 if (GetCompleteType(type)) {
3423 const clang::RecordType *record_type =
3424 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
3425 const clang::RecordDecl *record_decl = record_type->getDecl();
3426 if (record_decl) {
3427 const clang::CXXRecordDecl *cxx_record_decl =
3428 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
3429 if (cxx_record_decl)
3430 return cxx_record_decl->isPolymorphic();
3431 }
3432 }
3433 break;
3434
3435 default:
3436 break;
3437 }
3438 }
3439 return false;
3440}
3441
3442bool TypeSystemClang::IsPossibleDynamicType(lldb::opaque_compiler_type_t type,
3443 CompilerType *dynamic_pointee_type,
3444 bool check_cplusplus,
3445 bool check_objc) {
3446 clang::QualType pointee_qual_type;
3447 if (type) {
3448 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
3449 bool success = false;
3450 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3451 switch (type_class) {
3452 case clang::Type::Builtin:
3453 if (check_objc &&
3454 llvm::cast<clang::BuiltinType>(qual_type)->getKind() ==
3455 clang::BuiltinType::ObjCId) {
3456 if (dynamic_pointee_type)
3457 dynamic_pointee_type->SetCompilerType(this, type);
3458 return true;
3459 }
3460 break;
3461
3462 case clang::Type::ObjCObjectPointer:
3463 if (check_objc) {
3464 if (const auto *objc_pointee_type =
3465 qual_type->getPointeeType().getTypePtrOrNull()) {
3466 if (const auto *objc_object_type =
3467 llvm::dyn_cast_or_null<clang::ObjCObjectType>(
3468 objc_pointee_type)) {
3469 if (objc_object_type->isObjCClass())
3470 return false;
3471 }
3472 }
3473 if (dynamic_pointee_type)
3474 dynamic_pointee_type->SetCompilerType(
3475 this, llvm::cast<clang::ObjCObjectPointerType>(qual_type)
3476 ->getPointeeType()
3477 .getAsOpaquePtr());
3478 return true;
3479 }
3480 break;
3481
3482 case clang::Type::Pointer:
3483 pointee_qual_type =
3484 llvm::cast<clang::PointerType>(qual_type)->getPointeeType();
3485 success = true;
3486 break;
3487
3488 case clang::Type::LValueReference:
3489 case clang::Type::RValueReference:
3490 pointee_qual_type =
3491 llvm::cast<clang::ReferenceType>(qual_type)->getPointeeType();
3492 success = true;
3493 break;
3494
3495 default:
3496 break;
3497 }
3498
3499 if (success) {
3500 // Check to make sure what we are pointing too is a possible dynamic C++
3501 // type We currently accept any "void *" (in case we have a class that
3502 // has been watered down to an opaque pointer) and virtual C++ classes.
3503 const clang::Type::TypeClass pointee_type_class =
3504 pointee_qual_type.getCanonicalType()->getTypeClass();
3505 switch (pointee_type_class) {
3506 case clang::Type::Builtin:
3507 switch (llvm::cast<clang::BuiltinType>(pointee_qual_type)->getKind()) {
3508 case clang::BuiltinType::UnknownAny:
3509 case clang::BuiltinType::Void:
3510 if (dynamic_pointee_type)
3511 dynamic_pointee_type->SetCompilerType(
3512 this, pointee_qual_type.getAsOpaquePtr());
3513 return true;
3514 default:
3515 break;
3516 }
3517 break;
3518
3519 case clang::Type::Record:
3520 if (check_cplusplus) {
3521 clang::CXXRecordDecl *cxx_record_decl =
3522 pointee_qual_type->getAsCXXRecordDecl();
3523 if (cxx_record_decl) {
3524 bool is_complete = cxx_record_decl->isCompleteDefinition();
3525
3526 if (is_complete)
3527 success = cxx_record_decl->isDynamicClass();
3528 else {
3529 ClangASTMetadata *metadata = GetMetadata(cxx_record_decl);
3530 if (metadata)
3531 success = metadata->GetIsDynamicCXXType();
3532 else {
3533 is_complete = GetType(pointee_qual_type).GetCompleteType();
3534 if (is_complete)
3535 success = cxx_record_decl->isDynamicClass();
3536 else
3537 success = false;
3538 }
3539 }
3540
3541 if (success) {
3542 if (dynamic_pointee_type)
3543 dynamic_pointee_type->SetCompilerType(
3544 this, pointee_qual_type.getAsOpaquePtr());
3545 return true;
3546 }
3547 }
3548 }
3549 break;
3550
3551 case clang::Type::ObjCObject:
3552 case clang::Type::ObjCInterface:
3553 if (check_objc) {
3554 if (dynamic_pointee_type)
3555 dynamic_pointee_type->SetCompilerType(
3556 this, pointee_qual_type.getAsOpaquePtr());
3557 return true;
3558 }
3559 break;
3560
3561 default:
3562 break;
3563 }
3564 }
3565 }
3566 if (dynamic_pointee_type)
3567 dynamic_pointee_type->Clear();
3568 return false;
3569}
3570
3571bool TypeSystemClang::IsScalarType(lldb::opaque_compiler_type_t type) {
3572 if (!type)
3573 return false;
3574
3575 return (GetTypeInfo(type, nullptr) & eTypeIsScalar) != 0;
3576}
3577
3578bool TypeSystemClang::IsTypedefType(lldb::opaque_compiler_type_t type) {
3579 if (!type)
3580 return false;
3581 return RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef})
3582 ->getTypeClass() == clang::Type::Typedef;
3583}
3584
3585bool TypeSystemClang::IsVoidType(lldb::opaque_compiler_type_t type) {
3586 if (!type)
3587 return false;
3588 return GetCanonicalQualType(type)->isVoidType();
3589}
3590
3591bool TypeSystemClang::CanPassInRegisters(const CompilerType &type) {
3592 if (auto *record_decl =
3593 TypeSystemClang::GetAsRecordDecl(type)) {
3594 return record_decl->canPassInRegisters();
3595 }
3596 return false;
3597}
3598
3599bool TypeSystemClang::SupportsLanguage(lldb::LanguageType language) {
3600 return TypeSystemClangSupportsLanguage(language);
3601}
3602
3603Optional<std::string>
3604TypeSystemClang::GetCXXClassName(const CompilerType &type) {
3605 if (!type)
3606 return llvm::None;
3607
3608 clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
3609 if (qual_type.isNull())
3610 return llvm::None;
3611
3612 clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
3613 if (!cxx_record_decl)
3614 return llvm::None;
3615
3616 return std::string(cxx_record_decl->getIdentifier()->getNameStart());
3617}
3618
3619bool TypeSystemClang::IsCXXClassType(const CompilerType &type) {
3620 if (!type)
3621 return false;
3622
3623 clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
3624 return !qual_type.isNull() && qual_type->getAsCXXRecordDecl() != nullptr;
3625}
3626
3627bool TypeSystemClang::IsBeingDefined(lldb::opaque_compiler_type_t type) {
3628 if (!type)
3629 return false;
3630 clang::QualType qual_type(GetCanonicalQualType(type));
3631 const clang::TagType *tag_type = llvm::dyn_cast<clang::TagType>(qual_type);
3632 if (tag_type)
3633 return tag_type->isBeingDefined();
3634 return false;
3635}
3636
3637bool TypeSystemClang::IsObjCObjectPointerType(const CompilerType &type,
3638 CompilerType *class_type_ptr) {
3639 if (!ClangUtil::IsClangType(type))
3640 return false;
3641
3642 clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type));
3643
3644 if (!qual_type.isNull() && qual_type->isObjCObjectPointerType()) {
3645 if (class_type_ptr) {
3646 if (!qual_type->isObjCClassType() && !qual_type->isObjCIdType()) {
3647 const clang::ObjCObjectPointerType *obj_pointer_type =
3648 llvm::dyn_cast<clang::ObjCObjectPointerType>(qual_type);
3649 if (obj_pointer_type == nullptr)
3650 class_type_ptr->Clear();
3651 else
3652 class_type_ptr->SetCompilerType(
3653 type.GetTypeSystem(),
3654 clang::QualType(obj_pointer_type->getInterfaceType(), 0)
3655 .getAsOpaquePtr());
3656 }
3657 }
3658 return true;
3659 }
3660 if (class_type_ptr)
3661 class_type_ptr->Clear();
3662 return false;
3663}
3664
3665// Type Completion
3666
3667bool TypeSystemClang::GetCompleteType(lldb::opaque_compiler_type_t type) {
3668 if (!type)
3669 return false;
3670 const bool allow_completion = true;
3671 return GetCompleteQualType(&getASTContext(), GetQualType(type),
3672 allow_completion);
3673}
3674
3675ConstString TypeSystemClang::GetTypeName(lldb::opaque_compiler_type_t type) {
3676 if (!type)
3677 return ConstString();
3678
3679 clang::QualType qual_type(GetQualType(type));
3680
3681 // Remove certain type sugar from the name. Sugar such as elaborated types
3682 // or template types which only serve to improve diagnostics shouldn't
3683 // act as their own types from the user's perspective (e.g., formatter
3684 // shouldn't format a variable differently depending on how the ser has
3685 // specified the type. '::Type' and 'Type' should behave the same).
3686 // Typedefs and atomic derived types are not removed as they are actually
3687 // useful for identifiying specific types.
3688 qual_type = RemoveWrappingTypes(qual_type,
3689 {clang::Type::Typedef, clang::Type::Atomic});
3690
3691 // For a typedef just return the qualified name.
3692 if (const auto *typedef_type = qual_type->getAs<clang::TypedefType>()) {
3693 const clang::TypedefNameDecl *typedef_decl = typedef_type->getDecl();
3694 return ConstString(GetTypeNameForDecl(typedef_decl));
3695 }
3696
3697 return ConstString(qual_type.getAsString(GetTypePrintingPolicy()));
3698}
3699
3700ConstString
3701TypeSystemClang::GetDisplayTypeName(lldb::opaque_compiler_type_t type) {
3702 if (!type)
3703 return ConstString();
3704
3705 clang::QualType qual_type(GetQualType(type));
3706 clang::PrintingPolicy printing_policy(getASTContext().getPrintingPolicy());
3707 printing_policy.SuppressTagKeyword = true;
3708 printing_policy.SuppressScope = false;
3709 printing_policy.SuppressUnwrittenScope = true;
3710 printing_policy.SuppressInlineNamespace = true;
3711 return ConstString(qual_type.getAsString(printing_policy));
3712}
3713
3714uint32_t
3715TypeSystemClang::GetTypeInfo(lldb::opaque_compiler_type_t type,
3716 CompilerType *pointee_or_element_clang_type) {
3717 if (!type)
3718 return 0;
3719
3720 if (pointee_or_element_clang_type)
3721 pointee_or_element_clang_type->Clear();
3722
3723 clang::QualType qual_type =
3724 RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef});
3725
3726 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
3727 switch (type_class) {
3728 case clang::Type::Attributed:
3729 return GetTypeInfo(
3730 qual_type->getAs<clang::AttributedType>()
3731 ->getModifiedType().getAsOpaquePtr(),
3732 pointee_or_element_clang_type);
3733 case clang::Type::Builtin: {
3734 const clang::BuiltinType *builtin_type = llvm::dyn_cast<clang::BuiltinType>(
3735 qual_type->getCanonicalTypeInternal());
3736
3737 uint32_t builtin_type_flags = eTypeIsBuiltIn | eTypeHasValue;
3738 switch (builtin_type->getKind()) {
3739 case clang::BuiltinType::ObjCId:
3740 case clang::BuiltinType::ObjCClass:
3741 if (pointee_or_element_clang_type)
3742 pointee_or_element_clang_type->SetCompilerType(
3743 this, getASTContext().ObjCBuiltinClassTy.getAsOpaquePtr());
3744 builtin_type_flags |= eTypeIsPointer | eTypeIsObjC;
3745 break;
3746
3747 case clang::BuiltinType::ObjCSel:
3748 if (pointee_or_element_clang_type)
3749 pointee_or_element_clang_type->SetCompilerType(
3750 this, getASTContext().CharTy.getAsOpaquePtr());
3751 builtin_type_flags |= eTypeIsPointer | eTypeIsObjC;
3752 break;
3753
3754 case clang::BuiltinType::Bool:
3755 case clang::BuiltinType::Char_U:
3756 case clang::BuiltinType::UChar:
3757 case clang::BuiltinType::WChar_U:
3758 case clang::BuiltinType::Char16:
3759 case clang::BuiltinType::Char32:
3760 case clang::BuiltinType::UShort:
3761 case clang::BuiltinType::UInt:
3762 case clang::BuiltinType::ULong:
3763 case clang::BuiltinType::ULongLong:
3764 case clang::BuiltinType::UInt128:
3765 case clang::BuiltinType::Char_S:
3766 case clang::BuiltinType::SChar:
3767 case clang::BuiltinType::WChar_S:
3768 case clang::BuiltinType::Short:
3769 case clang::BuiltinType::Int:
3770 case clang::BuiltinType::Long:
3771 case clang::BuiltinType::LongLong:
3772 case clang::BuiltinType::Int128:
3773 case clang::BuiltinType::Float:
3774 case clang::BuiltinType::Double:
3775 case clang::BuiltinType::LongDouble:
3776 builtin_type_flags |= eTypeIsScalar;
3777 if (builtin_type->isInteger()) {
3778 builtin_type_flags |= eTypeIsInteger;
3779 if (builtin_type->isSignedInteger())
3780 builtin_type_flags |= eTypeIsSigned;
3781 } else if (builtin_type->isFloatingPoint())
3782 builtin_type_flags |= eTypeIsFloat;
3783 break;
3784 default:
3785 break;
3786 }
3787 return builtin_type_flags;
3788 }
3789
3790 case clang::Type::BlockPointer:
3791 if (pointee_or_element_clang_type)
3792 pointee_or_element_clang_type->SetCompilerType(
3793 this, qual_type->getPointeeType().getAsOpaquePtr());
3794 return eTypeIsPointer | eTypeHasChildren | eTypeIsBlock;
3795
3796 case clang::Type::Complex: {
3797 uint32_t complex_type_flags =
3798 eTypeIsBuiltIn | eTypeHasValue | eTypeIsComplex;
3799 const clang::ComplexType *complex_type = llvm::dyn_cast<clang::ComplexType>(
3800 qual_type->getCanonicalTypeInternal());
3801 if (complex_type) {
3802 clang::QualType complex_element_type(complex_type->getElementType());
3803 if (complex_element_type->isIntegerType())
3804 complex_type_flags |= eTypeIsFloat;
3805 else if (complex_element_type->isFloatingType())
3806 complex_type_flags |= eTypeIsInteger;
3807 }
3808 return complex_type_flags;
3809 } break;
3810
3811 case clang::Type::ConstantArray:
3812 case clang::Type::DependentSizedArray:
3813 case clang::Type::IncompleteArray:
3814 case clang::Type::VariableArray:
3815 if (pointee_or_element_clang_type)
3816 pointee_or_element_clang_type->SetCompilerType(
3817 this, llvm::cast<clang::ArrayType>(qual_type.getTypePtr())
3818 ->getElementType()
3819 .getAsOpaquePtr());
3820 return eTypeHasChildren | eTypeIsArray;
3821
3822 case clang::Type::DependentName:
3823 return 0;
3824 case clang::Type::DependentSizedExtVector:
3825 return eTypeHasChildren | eTypeIsVector;
3826 case clang::Type::DependentTemplateSpecialization:
3827 return eTypeIsTemplate;
3828
3829 case clang::Type::Enum:
3830 if (pointee_or_element_clang_type)
3831 pointee_or_element_clang_type->SetCompilerType(
3832 this, llvm::cast<clang::EnumType>(qual_type)
3833 ->getDecl()
3834 ->getIntegerType()
3835 .getAsOpaquePtr());
3836 return eTypeIsEnumeration | eTypeHasValue;
3837
3838 case clang::Type::FunctionProto:
3839 return eTypeIsFuncPrototype | eTypeHasValue;
3840 case clang::Type::FunctionNoProto:
3841 return eTypeIsFuncPrototype | eTypeHasValue;
3842 case clang::Type::InjectedClassName:
3843 return 0;
3844
3845 case clang::Type::LValueReference:
3846 case clang::Type::RValueReference:
3847 if (pointee_or_element_clang_type)
3848 pointee_or_element_clang_type->SetCompilerType(
3849 this, llvm::cast<clang::ReferenceType>(qual_type.getTypePtr())
3850 ->getPointeeType()
3851 .getAsOpaquePtr());
3852 return eTypeHasChildren | eTypeIsReference | eTypeHasValue;
3853
3854 case clang::Type::MemberPointer:
3855 return eTypeIsPointer | eTypeIsMember | eTypeHasValue;
3856
3857 case clang::Type::ObjCObjectPointer:
3858 if (pointee_or_element_clang_type)
3859 pointee_or_element_clang_type->SetCompilerType(
3860 this, qual_type->getPointeeType().getAsOpaquePtr());
3861 return eTypeHasChildren | eTypeIsObjC | eTypeIsClass | eTypeIsPointer |
3862 eTypeHasValue;
3863
3864 case clang::Type::ObjCObject:
3865 return eTypeHasChildren | eTypeIsObjC | eTypeIsClass;
3866 case clang::Type::ObjCInterface:
3867 return eTypeHasChildren | eTypeIsObjC | eTypeIsClass;
3868
3869 case clang::Type::Pointer:
3870 if (pointee_or_element_clang_type)
3871 pointee_or_element_clang_type->SetCompilerType(
3872 this, qual_type->getPointeeType().getAsOpaquePtr());
3873 return eTypeHasChildren | eTypeIsPointer | eTypeHasValue;
3874
3875 case clang::Type::Record:
3876 if (qual_type->getAsCXXRecordDecl())
3877 return eTypeHasChildren | eTypeIsClass | eTypeIsCPlusPlus;
3878 else
3879 return eTypeHasChildren | eTypeIsStructUnion;
3880 break;
3881 case clang::Type::SubstTemplateTypeParm:
3882 return eTypeIsTemplate;
3883 case clang::Type::TemplateTypeParm:
3884 return eTypeIsTemplate;
3885 case clang::Type::TemplateSpecialization:
3886 return eTypeIsTemplate;
3887
3888 case clang::Type::Typedef:
3889 return eTypeIsTypedef | GetType(llvm::cast<clang::TypedefType>(qual_type)
3890 ->getDecl()
3891 ->getUnderlyingType())
3892 .GetTypeInfo(pointee_or_element_clang_type);
3893 case clang::Type::UnresolvedUsing:
3894 return 0;
3895
3896 case clang::Type::ExtVector:
3897 case clang::Type::Vector: {
3898 uint32_t vector_type_flags = eTypeHasChildren | eTypeIsVector;
3899 const clang::VectorType *vector_type = llvm::dyn_cast<clang::VectorType>(
3900 qual_type->getCanonicalTypeInternal());
3901 if (vector_type) {
3902 if (vector_type->isIntegerType())
3903 vector_type_flags |= eTypeIsFloat;
3904 else if (vector_type->isFloatingType())
3905 vector_type_flags |= eTypeIsInteger;
3906 }
3907 return vector_type_flags;
3908 }
3909 default:
3910 return 0;
3911 }
3912 return 0;
3913}
3914
3915lldb::LanguageType
3916TypeSystemClang::GetMinimumLanguage(lldb::opaque_compiler_type_t type) {
3917 if (!type)
3918 return lldb::eLanguageTypeC;
3919
3920 // If the type is a reference, then resolve it to what it refers to first:
3921 clang::QualType qual_type(GetCanonicalQualType(type).getNonReferenceType());
3922 if (qual_type->isAnyPointerType()) {
3923 if (qual_type->isObjCObjectPointerType())
3924 return lldb::eLanguageTypeObjC;
3925 if (qual_type->getPointeeCXXRecordDecl())
3926 return lldb::eLanguageTypeC_plus_plus;
3927
3928 clang::QualType pointee_type(qual_type->getPointeeType());
3929 if (pointee_type->getPointeeCXXRecordDecl())
3930 return lldb::eLanguageTypeC_plus_plus;
3931 if (pointee_type->isObjCObjectOrInterfaceType())
3932 return lldb::eLanguageTypeObjC;
3933 if (pointee_type->isObjCClassType())
3934 return lldb::eLanguageTypeObjC;
3935 if (pointee_type.getTypePtr() ==
3936 getASTContext().ObjCBuiltinIdTy.getTypePtr())
3937 return lldb::eLanguageTypeObjC;
3938 } else {
3939 if (qual_type->isObjCObjectOrInterfaceType())
3940 return lldb::eLanguageTypeObjC;
3941 if (qual_type->getAsCXXRecordDecl())
3942 return lldb::eLanguageTypeC_plus_plus;
3943 switch (qual_type->getTypeClass()) {
3944 default:
3945 break;
3946 case clang::Type::Builtin:
3947 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
3948 default:
3949 case clang::BuiltinType::Void:
3950 case clang::BuiltinType::Bool:
3951 case clang::BuiltinType::Char_U:
3952 case clang::BuiltinType::UChar:
3953 case clang::BuiltinType::WChar_U:
3954 case clang::BuiltinType::Char16:
3955 case clang::BuiltinType::Char32:
3956 case clang::BuiltinType::UShort:
3957 case clang::BuiltinType::UInt:
3958 case clang::BuiltinType::ULong:
3959 case clang::BuiltinType::ULongLong:
3960 case clang::BuiltinType::UInt128:
3961 case clang::BuiltinType::Char_S:
3962 case clang::BuiltinType::SChar:
3963 case clang::BuiltinType::WChar_S:
3964 case clang::BuiltinType::Short:
3965 case clang::BuiltinType::Int:
3966 case clang::BuiltinType::Long:
3967 case clang::BuiltinType::LongLong:
3968 case clang::BuiltinType::Int128:
3969 case clang::BuiltinType::Float:
3970 case clang::BuiltinType::Double:
3971 case clang::BuiltinType::LongDouble:
3972 break;
3973
3974 case clang::BuiltinType::NullPtr:
3975 return eLanguageTypeC_plus_plus;
3976
3977 case clang::BuiltinType::ObjCId:
3978 case clang::BuiltinType::ObjCClass:
3979 case clang::BuiltinType::ObjCSel:
3980 return eLanguageTypeObjC;
3981
3982 case clang::BuiltinType::Dependent:
3983 case clang::BuiltinType::Overload:
3984 case clang::BuiltinType::BoundMember:
3985 case clang::BuiltinType::UnknownAny:
3986 break;
3987 }
3988 break;
3989 case clang::Type::Typedef:
3990 return GetType(llvm::cast<clang::TypedefType>(qual_type)
3991 ->getDecl()
3992 ->getUnderlyingType())
3993 .GetMinimumLanguage();
3994 }
3995 }
3996 return lldb::eLanguageTypeC;
3997}
3998
3999lldb::TypeClass
4000TypeSystemClang::GetTypeClass(lldb::opaque_compiler_type_t type) {
4001 if (!type)
4002 return lldb::eTypeClassInvalid;
4003
4004 clang::QualType qual_type =
4005 RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef});
4006
4007 switch (qual_type->getTypeClass()) {
4008 case clang::Type::Atomic:
4009 case clang::Type::Auto:
4010 case clang::Type::Decltype:
4011 case clang::Type::Elaborated:
4012 case clang::Type::Paren:
4013 case clang::Type::TypeOf:
4014 case clang::Type::TypeOfExpr:
4015 llvm_unreachable("Handled in RemoveWrappingTypes!");
4016 case clang::Type::UnaryTransform:
4017 break;
4018 case clang::Type::FunctionNoProto:
4019 return lldb::eTypeClassFunction;
4020 case clang::Type::FunctionProto:
4021 return lldb::eTypeClassFunction;
4022 case clang::Type::IncompleteArray:
4023 return lldb::eTypeClassArray;
4024 case clang::Type::VariableArray:
4025 return lldb::eTypeClassArray;
4026 case clang::Type::ConstantArray:
4027 return lldb::eTypeClassArray;
4028 case clang::Type::DependentSizedArray:
4029 return lldb::eTypeClassArray;
4030 case clang::Type::DependentSizedExtVector:
4031 return lldb::eTypeClassVector;
4032 case clang::Type::DependentVector:
4033 return lldb::eTypeClassVector;
4034 case clang::Type::ExtVector:
4035 return lldb::eTypeClassVector;
4036 case clang::Type::Vector:
4037 return lldb::eTypeClassVector;
4038 case clang::Type::Builtin:
4039 // Ext-Int is just an integer type.
4040 case clang::Type::ExtInt:
4041 case clang::Type::DependentExtInt:
4042 return lldb::eTypeClassBuiltin;
4043 case clang::Type::ObjCObjectPointer:
4044 return lldb::eTypeClassObjCObjectPointer;
4045 case clang::Type::BlockPointer:
4046 return lldb::eTypeClassBlockPointer;
4047 case clang::Type::Pointer:
4048 return lldb::eTypeClassPointer;
4049 case clang::Type::LValueReference:
4050 return lldb::eTypeClassReference;
4051 case clang::Type::RValueReference:
4052 return lldb::eTypeClassReference;
4053 case clang::Type::MemberPointer:
4054 return lldb::eTypeClassMemberPointer;
4055 case clang::Type::Complex:
4056 if (qual_type->isComplexType())
4057 return lldb::eTypeClassComplexFloat;
4058 else
4059 return lldb::eTypeClassComplexInteger;
4060 case clang::Type::ObjCObject:
4061 return lldb::eTypeClassObjCObject;
4062 case clang::Type::ObjCInterface:
4063 return lldb::eTypeClassObjCInterface;
4064 case clang::Type::Record: {
4065 const clang::RecordType *record_type =
4066 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
4067 const clang::RecordDecl *record_decl = record_type->getDecl();
4068 if (record_decl->isUnion())
4069 return lldb::eTypeClassUnion;
4070 else if (record_decl->isStruct())
4071 return lldb::eTypeClassStruct;
4072 else
4073 return lldb::eTypeClassClass;
4074 } break;
4075 case clang::Type::Enum:
4076 return lldb::eTypeClassEnumeration;
4077 case clang::Type::Typedef:
4078 return lldb::eTypeClassTypedef;
4079 case clang::Type::UnresolvedUsing:
4080 break;
4081
4082 case clang::Type::Attributed:
4083 break;
4084 case clang::Type::TemplateTypeParm:
4085 break;
4086 case clang::Type::SubstTemplateTypeParm:
4087 break;
4088 case clang::Type::SubstTemplateTypeParmPack:
4089 break;
4090 case clang::Type::InjectedClassName:
4091 break;
4092 case clang::Type::DependentName:
4093 break;
4094 case clang::Type::DependentTemplateSpecialization:
4095 break;
4096 case clang::Type::PackExpansion:
4097 break;
4098
4099 case clang::Type::TemplateSpecialization:
4100 break;
4101 case clang::Type::DeducedTemplateSpecialization:
4102 break;
4103 case clang::Type::Pipe:
4104 break;
4105
4106 // pointer type decayed from an array or function type.
4107 case clang::Type::Decayed:
4108 break;
4109 case clang::Type::Adjusted:
4110 break;
4111 case clang::Type::ObjCTypeParam:
4112 break;
4113
4114 case clang::Type::DependentAddressSpace:
4115 break;
4116 case clang::Type::MacroQualified:
4117 break;
4118
4119 // Matrix types that we're not sure how to display at the moment.
4120 case clang::Type::ConstantMatrix:
4121 case clang::Type::DependentSizedMatrix:
4122 break;
4123 }
4124 // We don't know hot to display this type...
4125 return lldb::eTypeClassOther;
4126}
4127
4128unsigned TypeSystemClang::GetTypeQualifiers(lldb::opaque_compiler_type_t type) {
4129 if (type)
4130 return GetQualType(type).getQualifiers().getCVRQualifiers();
4131 return 0;
4132}
4133
4134// Creating related types
4135
4136CompilerType
4137TypeSystemClang::GetArrayElementType(lldb::opaque_compiler_type_t type,
4138 ExecutionContextScope *exe_scope) {
4139 if (type) {
4140 clang::QualType qual_type(GetQualType(type));
4141
4142 const clang::Type *array_eletype =
4143 qual_type.getTypePtr()->getArrayElementTypeNoTypeQual();
4144
4145 if (!array_eletype)
4146 return CompilerType();
4147
4148 return GetType(clang::QualType(array_eletype, 0));
4149 }
4150 return CompilerType();
4151}
4152
4153CompilerType TypeSystemClang::GetArrayType(lldb::opaque_compiler_type_t type,
4154 uint64_t size) {
4155 if (type) {
4156 clang::QualType qual_type(GetCanonicalQualType(type));
4157 clang::ASTContext &ast_ctx = getASTContext();
4158 if (size != 0)
4159 return GetType(ast_ctx.getConstantArrayType(
4160 qual_type, llvm::APInt(64, size), nullptr,
4161 clang::ArrayType::ArraySizeModifier::Normal, 0));
4162 else
4163 return GetType(ast_ctx.getIncompleteArrayType(
4164 qual_type, clang::ArrayType::ArraySizeModifier::Normal, 0));
4165 }
4166
4167 return CompilerType();
4168}
4169
4170CompilerType
4171TypeSystemClang::GetCanonicalType(lldb::opaque_compiler_type_t type) {
4172 if (type)
4173 return GetType(GetCanonicalQualType(type));
4174 return CompilerType();
4175}
4176
4177static clang::QualType GetFullyUnqualifiedType_Impl(clang::ASTContext *ast,
4178 clang::QualType qual_type) {
4179 if (qual_type->isPointerType())
4180 qual_type = ast->getPointerType(
4181 GetFullyUnqualifiedType_Impl(ast, qual_type->getPointeeType()));
4182 else
4183 qual_type = qual_type.getUnqualifiedType();
4184 qual_type.removeLocalConst();
4185 qual_type.removeLocalRestrict();
4186 qual_type.removeLocalVolatile();
4187 return qual_type;
4188}
4189
4190CompilerType
4191TypeSystemClang::GetFullyUnqualifiedType(lldb::opaque_compiler_type_t type) {
4192 if (type)
4193 return GetType(
4194 GetFullyUnqualifiedType_Impl(&getASTContext(), GetQualType(type)));
4195 return CompilerType();
4196}
4197
4198CompilerType
4199TypeSystemClang::GetEnumerationIntegerType(lldb::opaque_compiler_type_t type) {
4200 if (type)
4201 return GetEnumerationIntegerType(GetType(GetCanonicalQualType(type)));
4202 return CompilerType();
4203}
4204
4205int TypeSystemClang::GetFunctionArgumentCount(
4206 lldb::opaque_compiler_type_t type) {
4207 if (type) {
4208 const clang::FunctionProtoType *func =
4209 llvm::dyn_cast<clang::FunctionProtoType>(GetCanonicalQualType(type));
4210 if (func)
4211 return func->getNumParams();
4212 }
4213 return -1;
4214}
4215
4216CompilerType TypeSystemClang::GetFunctionArgumentTypeAtIndex(
4217 lldb::opaque_compiler_type_t type, size_t idx) {
4218 if (type) {
4219 const clang::FunctionProtoType *func =
4220 llvm::dyn_cast<clang::FunctionProtoType>(GetQualType(type));
4221 if (func) {
4222 const uint32_t num_args = func->getNumParams();
4223 if (idx < num_args)
4224 return GetType(func->getParamType(idx));
4225 }
4226 }
4227 return CompilerType();
4228}
4229
4230CompilerType
4231TypeSystemClang::GetFunctionReturnType(lldb::opaque_compiler_type_t type) {
4232 if (type) {
4233 clang::QualType qual_type(GetQualType(type));
4234 const clang::FunctionProtoType *func =
4235 llvm::dyn_cast<clang::FunctionProtoType>(qual_type.getTypePtr());
4236 if (func)
4237 return GetType(func->getReturnType());
4238 }
4239 return CompilerType();
4240}
4241
4242size_t
4243TypeSystemClang::GetNumMemberFunctions(lldb::opaque_compiler_type_t type) {
4244 size_t num_functions = 0;
4245 if (type) {
4246 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
4247 switch (qual_type->getTypeClass()) {
4248 case clang::Type::Record:
4249 if (GetCompleteQualType(&getASTContext(), qual_type)) {
4250 const clang::RecordType *record_type =
4251 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
4252 const clang::RecordDecl *record_decl = record_type->getDecl();
4253 assert(record_decl);
4254 const clang::CXXRecordDecl *cxx_record_decl =
4255 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
4256 if (cxx_record_decl)
4257 num_functions = std::distance(cxx_record_decl->method_begin(),
4258 cxx_record_decl->method_end());
4259 }
4260 break;
4261
4262 case clang::Type::ObjCObjectPointer: {
4263 const clang::ObjCObjectPointerType *objc_class_type =
4264 qual_type->getAs<clang::ObjCObjectPointerType>();
4265 const clang::ObjCInterfaceType *objc_interface_type =
4266 objc_class_type->getInterfaceType();
4267 if (objc_interface_type &&
4268 GetCompleteType(static_cast<lldb::opaque_compiler_type_t>(
4269 const_cast<clang::ObjCInterfaceType *>(objc_interface_type)))) {
4270 clang::ObjCInterfaceDecl *class_interface_decl =
4271 objc_interface_type->getDecl();
4272 if (class_interface_decl) {
4273 num_functions = std::distance(class_interface_decl->meth_begin(),
4274 class_interface_decl->meth_end());
4275 }
4276 }
4277 break;
4278 }
4279
4280 case clang::Type::ObjCObject:
4281 case clang::Type::ObjCInterface:
4282 if (GetCompleteType(type)) {
4283 const clang::ObjCObjectType *objc_class_type =
4284 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
4285 if (objc_class_type) {
4286 clang::ObjCInterfaceDecl *class_interface_decl =
4287 objc_class_type->getInterface();
4288 if (class_interface_decl)
4289 num_functions = std::distance(class_interface_decl->meth_begin(),
4290 class_interface_decl->meth_end());
4291 }
4292 }
4293 break;
4294
4295 default:
4296 break;
4297 }
4298 }
4299 return num_functions;
4300}
4301
4302TypeMemberFunctionImpl
4303TypeSystemClang::GetMemberFunctionAtIndex(lldb::opaque_compiler_type_t type,
4304 size_t idx) {
4305 std::string name;
4306 MemberFunctionKind kind(MemberFunctionKind::eMemberFunctionKindUnknown);
4307 CompilerType clang_type;
4308 CompilerDecl clang_decl;
4309 if (type) {
4310 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
4311 switch (qual_type->getTypeClass()) {
4312 case clang::Type::Record:
4313 if (GetCompleteQualType(&getASTContext(), qual_type)) {
4314 const clang::RecordType *record_type =
4315 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
4316 const clang::RecordDecl *record_decl = record_type->getDecl();
4317 assert(record_decl);
4318 const clang::CXXRecordDecl *cxx_record_decl =
4319 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
4320 if (cxx_record_decl) {
4321 auto method_iter = cxx_record_decl->method_begin();
4322 auto method_end = cxx_record_decl->method_end();
4323 if (idx <
4324 static_cast<size_t>(std::distance(method_iter, method_end))) {
4325 std::advance(method_iter, idx);
4326 clang::CXXMethodDecl *cxx_method_decl =
4327 method_iter->getCanonicalDecl();
4328 if (cxx_method_decl) {
4329 name = cxx_method_decl->getDeclName().getAsString();
4330 if (cxx_method_decl->isStatic())
4331 kind = lldb::eMemberFunctionKindStaticMethod;
4332 else if (llvm::isa<clang::CXXConstructorDecl>(cxx_method_decl))
4333 kind = lldb::eMemberFunctionKindConstructor;
4334 else if (llvm::isa<clang::CXXDestructorDecl>(cxx_method_decl))
4335 kind = lldb::eMemberFunctionKindDestructor;
4336 else
4337 kind = lldb::eMemberFunctionKindInstanceMethod;
4338 clang_type = GetType(cxx_method_decl->getType());
4339 clang_decl = GetCompilerDecl(cxx_method_decl);
4340 }
4341 }
4342 }
4343 }
4344 break;
4345
4346 case clang::Type::ObjCObjectPointer: {
4347 const clang::ObjCObjectPointerType *objc_class_type =
4348 qual_type->getAs<clang::ObjCObjectPointerType>();
4349 const clang::ObjCInterfaceType *objc_interface_type =
4350 objc_class_type->getInterfaceType();
4351 if (objc_interface_type &&
4352 GetCompleteType(static_cast<lldb::opaque_compiler_type_t>(
4353 const_cast<clang::ObjCInterfaceType *>(objc_interface_type)))) {
4354 clang::ObjCInterfaceDecl *class_interface_decl =
4355 objc_interface_type->getDecl();
4356 if (class_interface_decl) {
4357 auto method_iter = class_interface_decl->meth_begin();
4358 auto method_end = class_interface_decl->meth_end();
4359 if (idx <
4360 static_cast<size_t>(std::distance(method_iter, method_end))) {
4361 std::advance(method_iter, idx);
4362 clang::ObjCMethodDecl *objc_method_decl =
4363 method_iter->getCanonicalDecl();
4364 if (objc_method_decl) {
4365 clang_decl = GetCompilerDecl(objc_method_decl);
4366 name = objc_method_decl->getSelector().getAsString();
4367 if (objc_method_decl->isClassMethod())
4368 kind = lldb::eMemberFunctionKindStaticMethod;
4369 else
4370 kind = lldb::eMemberFunctionKindInstanceMethod;
4371 }
4372 }
4373 }
4374 }
4375 break;
4376 }
4377
4378 case clang::Type::ObjCObject:
4379 case clang::Type::ObjCInterface:
4380 if (GetCompleteType(type)) {
4381 const clang::ObjCObjectType *objc_class_type =
4382 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
4383 if (objc_class_type) {
4384 clang::ObjCInterfaceDecl *class_interface_decl =
4385 objc_class_type->getInterface();
4386 if (class_interface_decl) {
4387 auto method_iter = class_interface_decl->meth_begin();
4388 auto method_end = class_interface_decl->meth_end();
4389 if (idx <
4390 static_cast<size_t>(std::distance(method_iter, method_end))) {
4391 std::advance(method_iter, idx);
4392 clang::ObjCMethodDecl *objc_method_decl =
4393 method_iter->getCanonicalDecl();
4394 if (objc_method_decl) {
4395 clang_decl = GetCompilerDecl(objc_method_decl);
4396 name = objc_method_decl->getSelector().getAsString();
4397 if (objc_method_decl->isClassMethod())
4398 kind = lldb::eMemberFunctionKindStaticMethod;
4399 else
4400 kind = lldb::eMemberFunctionKindInstanceMethod;
4401 }
4402 }
4403 }
4404 }
4405 }
4406 break;
4407
4408 default:
4409 break;
4410 }
4411 }
4412
4413 if (kind == eMemberFunctionKindUnknown)
4414 return TypeMemberFunctionImpl();
4415 else
4416 return TypeMemberFunctionImpl(clang_type, clang_decl, name, kind);
4417}
4418
4419CompilerType
4420TypeSystemClang::GetNonReferenceType(lldb::opaque_compiler_type_t type) {
4421 if (type)
4422 return GetType(GetQualType(type).getNonReferenceType());
4423 return CompilerType();
4424}
4425
4426CompilerType
4427TypeSystemClang::GetPointeeType(lldb::opaque_compiler_type_t type) {
4428 if (type) {
4429 clang::QualType qual_type(GetQualType(type));
4430 return GetType(qual_type.getTypePtr()->getPointeeType());
4431 }
4432 return CompilerType();
4433}
4434
4435CompilerType
4436TypeSystemClang::GetPointerType(lldb::opaque_compiler_type_t type) {
4437 if (type) {
4438 clang::QualType qual_type(GetQualType(type));
4439
4440 switch (qual_type.getDesugaredType(getASTContext())->getTypeClass()) {
4441 case clang::Type::ObjCObject:
4442 case clang::Type::ObjCInterface:
4443 return GetType(getASTContext().getObjCObjectPointerType(qual_type));
4444
4445 default:
4446 return GetType(getASTContext().getPointerType(qual_type));
4447 }
4448 }
4449 return CompilerType();
4450}
4451
4452CompilerType
4453TypeSystemClang::GetLValueReferenceType(lldb::opaque_compiler_type_t type) {
4454 if (type)
4455 return GetType(getASTContext().getLValueReferenceType(GetQualType(type)));
4456 else
4457 return CompilerType();
4458}
4459
4460CompilerType
4461TypeSystemClang::GetRValueReferenceType(lldb::opaque_compiler_type_t type) {
4462 if (type)
4463 return GetType(getASTContext().getRValueReferenceType(GetQualType(type)));
4464 else
4465 return CompilerType();
4466}
4467
4468CompilerType TypeSystemClang::GetAtomicType(lldb::opaque_compiler_type_t type) {
4469 if (!type)
4470 return CompilerType();
4471 return GetType(getASTContext().getAtomicType(GetQualType(type)));
4472}
4473
4474CompilerType
4475TypeSystemClang::AddConstModifier(lldb::opaque_compiler_type_t type) {
4476 if (type) {
4477 clang::QualType result(GetQualType(type));
4478 result.addConst();
4479 return GetType(result);
4480 }
4481 return CompilerType();
4482}
4483
4484CompilerType
4485TypeSystemClang::AddVolatileModifier(lldb::opaque_compiler_type_t type) {
4486 if (type) {
4487 clang::QualType result(GetQualType(type));
4488 result.addVolatile();
4489 return GetType(result);
4490 }
4491 return CompilerType();
4492}
4493
4494CompilerType
4495TypeSystemClang::AddRestrictModifier(lldb::opaque_compiler_type_t type) {
4496 if (type) {
4497 clang::QualType result(GetQualType(type));
4498 result.addRestrict();
4499 return GetType(result);
4500 }
4501 return CompilerType();
4502}
4503
4504CompilerType TypeSystemClang::CreateTypedef(
4505 lldb::opaque_compiler_type_t type, const char *typedef_name,
4506 const CompilerDeclContext &compiler_decl_ctx, uint32_t payload) {
4507 if (type && typedef_name && typedef_name[0]) {
4508 clang::ASTContext &clang_ast = getASTContext();
4509 clang::QualType qual_type(GetQualType(type));
4510
4511 clang::DeclContext *decl_ctx =
4512 TypeSystemClang::DeclContextGetAsDeclContext(compiler_decl_ctx);
4513 if (!decl_ctx)
4514 decl_ctx = getASTContext().getTranslationUnitDecl();
4515
4516 clang::TypedefDecl *decl =
4517 clang::TypedefDecl::CreateDeserialized(clang_ast, 0);
4518 decl->setDeclContext(decl_ctx);
4519 decl->setDeclName(&clang_ast.Idents.get(typedef_name));
4520 decl->setTypeSourceInfo(clang_ast.getTrivialTypeSourceInfo(qual_type));
4521 decl_ctx->addDecl(decl);
4522 SetOwningModule(decl, TypePayloadClang(payload).GetOwningModule());
4523
4524 clang::TagDecl *tdecl = nullptr;
4525 if (!qual_type.isNull()) {
4526 if (const clang::RecordType *rt = qual_type->getAs<clang::RecordType>())
4527 tdecl = rt->getDecl();
4528 if (const clang::EnumType *et = qual_type->getAs<clang::EnumType>())
4529 tdecl = et->getDecl();
4530 }
4531
4532 // Check whether this declaration is an anonymous struct, union, or enum,
4533 // hidden behind a typedef. If so, we try to check whether we have a
4534 // typedef tag to attach to the original record declaration
4535 if (tdecl && !tdecl->getIdentifier() && !tdecl->getTypedefNameForAnonDecl())
4536 tdecl->setTypedefNameForAnonDecl(decl);
4537
4538 decl->setAccess(clang::AS_public); // TODO respect proper access specifier
4539
4540 // Get a uniqued clang::QualType for the typedef decl type
4541 return GetType(clang_ast.getTypedefType(decl));
4542 }
4543 return CompilerType();
4544}
4545
4546CompilerType
4547TypeSystemClang::GetTypedefedType(lldb::opaque_compiler_type_t type) {
4548 if (type) {
4549 const clang::TypedefType *typedef_type = llvm::dyn_cast<clang::TypedefType>(
4550 RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef}));
4551 if (typedef_type)
4552 return GetType(typedef_type->getDecl()->getUnderlyingType());
4553 }
4554 return CompilerType();
4555}
4556
4557// Create related types using the current type's AST
4558
4559CompilerType TypeSystemClang::GetBasicTypeFromAST(lldb::BasicType basic_type) {
4560 return TypeSystemClang::GetBasicType(basic_type);
4561}
4562// Exploring the type
4563
4564const llvm::fltSemantics &
4565TypeSystemClang::GetFloatTypeSemantics(size_t byte_size) {
4566 clang::ASTContext &ast = getASTContext();
4567 const size_t bit_size = byte_size * 8;
4568 if (bit_size == ast.getTypeSize(ast.FloatTy))
4569 return ast.getFloatTypeSemantics(ast.FloatTy);
4570 else if (bit_size == ast.getTypeSize(ast.DoubleTy))
4571 return ast.getFloatTypeSemantics(ast.DoubleTy);
4572 else if (bit_size == ast.getTypeSize(ast.LongDoubleTy))
4573 return ast.getFloatTypeSemantics(ast.LongDoubleTy);
4574 else if (bit_size == ast.getTypeSize(ast.HalfTy))
4575 return ast.getFloatTypeSemantics(ast.HalfTy);
4576 return llvm::APFloatBase::Bogus();
4577}
4578
4579Optional<uint64_t>
4580TypeSystemClang::GetBitSize(lldb::opaque_compiler_type_t type,
4581 ExecutionContextScope *exe_scope) {
4582 if (GetCompleteType(type)) {
4583 clang::QualType qual_type(GetCanonicalQualType(type));
4584 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
4585 switch (type_class) {
4586 case clang::Type::Record:
4587 if (GetCompleteType(type))
4588 return getASTContext().getTypeSize(qual_type);
4589 else
4590 return None;
4591 break;
4592
4593 case clang::Type::ObjCInterface:
4594 case clang::Type::ObjCObject: {
4595 ExecutionContext exe_ctx(exe_scope);
4596 Process *process = exe_ctx.GetProcessPtr();
4597 if (process) {
4598 ObjCLanguageRuntime *objc_runtime = ObjCLanguageRuntime::Get(*process);
4599 if (objc_runtime) {
4600 uint64_t bit_size = 0;
4601 if (objc_runtime->GetTypeBitSize(GetType(qual_type), bit_size))
4602 return bit_size;
4603 }
4604 } else {
4605 static bool g_printed = false;
4606 if (!g_printed) {
4607 StreamString s;
4608 DumpTypeDescription(type, &s);
4609
4610 llvm::outs() << "warning: trying to determine the size of type ";
4611 llvm::outs() << s.GetString() << "\n";
4612 llvm::outs() << "without a valid ExecutionContext. this is not "
4613 "reliable. please file a bug against LLDB.\n";
4614 llvm::outs() << "backtrace:\n";
4615 llvm::sys::PrintStackTrace(llvm::outs());
4616 llvm::outs() << "\n";
4617 g_printed = true;
4618 }
4619 }
4620 }
4621 LLVM_FALLTHROUGH;
4622 default:
4623 const uint32_t bit_size = getASTContext().getTypeSize(qual_type);
4624 if (bit_size == 0) {
4625 if (qual_type->isIncompleteArrayType())
4626 return getASTContext().getTypeSize(
4627 qual_type->getArrayElementTypeNoTypeQual()
4628 ->getCanonicalTypeUnqualified());
4629 }
4630 if (qual_type->isObjCObjectOrInterfaceType())
4631 return bit_size +
4632 getASTContext().getTypeSize(getASTContext().ObjCBuiltinClassTy);
4633 // Function types actually have a size of 0, that's not an error.
4634 if (qual_type->isFunctionProtoType())
4635 return bit_size;
4636 if (bit_size)
4637 return bit_size;
4638 }
4639 }
4640 return None;
4641}
4642
4643llvm::Optional<size_t>
4644TypeSystemClang::GetTypeBitAlign(lldb::opaque_compiler_type_t type,
4645 ExecutionContextScope *exe_scope) {
4646 if (GetCompleteType(type))
4647 return getASTContext().getTypeAlign(GetQualType(type));
4648 return {};
4649}
4650
4651lldb::Encoding TypeSystemClang::GetEncoding(lldb::opaque_compiler_type_t type,
4652 uint64_t &count) {
4653 if (!type)
4654 return lldb::eEncodingInvalid;
4655
4656 count = 1;
4657 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
4658
4659 switch (qual_type->getTypeClass()) {
4660 case clang::Type::Atomic:
4661 case clang::Type::Auto:
4662 case clang::Type::Decltype:
4663 case clang::Type::Elaborated:
4664 case clang::Type::Paren:
4665 case clang::Type::Typedef:
4666 case clang::Type::TypeOf:
4667 case clang::Type::TypeOfExpr:
4668 llvm_unreachable("Handled in RemoveWrappingTypes!");
4669
4670 case clang::Type::UnaryTransform:
4671 break;
4672
4673 case clang::Type::FunctionNoProto:
4674 case clang::Type::FunctionProto:
4675 break;
4676
4677 case clang::Type::IncompleteArray:
4678 case clang::Type::VariableArray:
4679 break;
4680
4681 case clang::Type::ConstantArray:
4682 break;
4683
4684 case clang::Type::DependentVector:
4685 case clang::Type::ExtVector:
4686 case clang::Type::Vector:
4687 // TODO: Set this to more than one???
4688 break;
4689
4690 case clang::Type::ExtInt:
4691 case clang::Type::DependentExtInt:
4692 return qual_type->isUnsignedIntegerType() ? lldb::eEncodingUint
4693 : lldb::eEncodingSint;
4694
4695 case clang::Type::Builtin:
4696 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
4697 case clang::BuiltinType::Void:
4698 break;
4699
4700 case clang::BuiltinType::Bool:
4701 case clang::BuiltinType::Char_S:
4702 case clang::BuiltinType::SChar:
4703 case clang::BuiltinType::WChar_S:
4704 case clang::BuiltinType::Short:
4705 case clang::BuiltinType::Int:
4706 case clang::BuiltinType::Long:
4707 case clang::BuiltinType::LongLong:
4708 case clang::BuiltinType::Int128:
4709 return lldb::eEncodingSint;
4710
4711 case clang::BuiltinType::Char_U:
4712 case clang::BuiltinType::UChar:
4713 case clang::BuiltinType::WChar_U:
4714 case clang::BuiltinType::Char8:
4715 case clang::BuiltinType::Char16:
4716 case clang::BuiltinType::Char32:
4717 case clang::BuiltinType::UShort:
4718 case clang::BuiltinType::UInt:
4719 case clang::BuiltinType::ULong:
4720 case clang::BuiltinType::ULongLong:
4721 case clang::BuiltinType::UInt128:
4722 return lldb::eEncodingUint;
4723
4724 // Fixed point types. Note that they are currently ignored.
4725 case clang::BuiltinType::ShortAccum:
4726 case clang::BuiltinType::Accum:
4727 case clang::BuiltinType::LongAccum:
4728 case clang::BuiltinType::UShortAccum:
4729 case clang::BuiltinType::UAccum:
4730 case clang::BuiltinType::ULongAccum:
4731 case clang::BuiltinType::ShortFract:
4732 case clang::BuiltinType::Fract:
4733 case clang::BuiltinType::LongFract:
4734 case clang::BuiltinType::UShortFract:
4735 case clang::BuiltinType::UFract:
4736 case clang::BuiltinType::ULongFract:
4737 case clang::BuiltinType::SatShortAccum:
4738 case clang::BuiltinType::SatAccum:
4739 case clang::BuiltinType::SatLongAccum:
4740 case clang::BuiltinType::SatUShortAccum:
4741 case clang::BuiltinType::SatUAccum:
4742 case clang::BuiltinType::SatULongAccum:
4743 case clang::BuiltinType::SatShortFract:
4744 case clang::BuiltinType::SatFract:
4745 case clang::BuiltinType::SatLongFract:
4746 case clang::BuiltinType::SatUShortFract:
4747 case clang::BuiltinType::SatUFract:
4748 case clang::BuiltinType::SatULongFract:
4749 break;
4750
4751 case clang::BuiltinType::Half:
4752 case clang::BuiltinType::Float:
4753 case clang::BuiltinType::Float16:
4754 case clang::BuiltinType::Float128:
4755 case clang::BuiltinType::Double:
4756 case clang::BuiltinType::LongDouble:
4757 case clang::BuiltinType::BFloat16:
4758 return lldb::eEncodingIEEE754;
4759
4760 case clang::BuiltinType::ObjCClass:
4761 case clang::BuiltinType::ObjCId:
4762 case clang::BuiltinType::ObjCSel:
4763 return lldb::eEncodingUint;
4764
4765 case clang::BuiltinType::NullPtr:
4766 return lldb::eEncodingUint;
4767
4768 case clang::BuiltinType::Kind::ARCUnbridgedCast:
4769 case clang::BuiltinType::Kind::BoundMember:
4770 case clang::BuiltinType::Kind::BuiltinFn:
4771 case clang::BuiltinType::Kind::Dependent:
4772 case clang::BuiltinType::Kind::OCLClkEvent:
4773 case clang::BuiltinType::Kind::OCLEvent:
4774 case clang::BuiltinType::Kind::OCLImage1dRO:
4775 case clang::BuiltinType::Kind::OCLImage1dWO:
4776 case clang::BuiltinType::Kind::OCLImage1dRW:
4777 case clang::BuiltinType::Kind::OCLImage1dArrayRO:
4778 case clang::BuiltinType::Kind::OCLImage1dArrayWO:
4779 case clang::BuiltinType::Kind::OCLImage1dArrayRW:
4780 case clang::BuiltinType::Kind::OCLImage1dBufferRO:
4781 case clang::BuiltinType::Kind::OCLImage1dBufferWO:
4782 case clang::BuiltinType::Kind::OCLImage1dBufferRW:
4783 case clang::BuiltinType::Kind::OCLImage2dRO:
4784 case clang::BuiltinType::Kind::OCLImage2dWO:
4785 case clang::BuiltinType::Kind::OCLImage2dRW:
4786 case clang::BuiltinType::Kind::OCLImage2dArrayRO:
4787 case clang::BuiltinType::Kind::OCLImage2dArrayWO:
4788 case clang::BuiltinType::Kind::OCLImage2dArrayRW:
4789 case clang::BuiltinType::Kind::OCLImage2dArrayDepthRO:
4790 case clang::BuiltinType::Kind::OCLImage2dArrayDepthWO:
4791 case clang::BuiltinType::Kind::OCLImage2dArrayDepthRW:
4792 case clang::BuiltinType::Kind::OCLImage2dArrayMSAARO:
4793 case clang::BuiltinType::Kind::OCLImage2dArrayMSAAWO:
4794 case clang::BuiltinType::Kind::OCLImage2dArrayMSAARW:
4795 case clang::BuiltinType::Kind::OCLImage2dArrayMSAADepthRO:
4796 case clang::BuiltinType::Kind::OCLImage2dArrayMSAADepthWO:
4797 case clang::BuiltinType::Kind::OCLImage2dArrayMSAADepthRW:
4798 case clang::BuiltinType::Kind::OCLImage2dDepthRO:
4799 case clang::BuiltinType::Kind::OCLImage2dDepthWO:
4800 case clang::BuiltinType::Kind::OCLImage2dDepthRW:
4801 case clang::BuiltinType::Kind::OCLImage2dMSAARO:
4802 case clang::BuiltinType::Kind::OCLImage2dMSAAWO:
4803 case clang::BuiltinType::Kind::OCLImage2dMSAARW:
4804 case clang::BuiltinType::Kind::OCLImage2dMSAADepthRO:
4805 case clang::BuiltinType::Kind::OCLImage2dMSAADepthWO:
4806 case clang::BuiltinType::Kind::OCLImage2dMSAADepthRW:
4807 case clang::BuiltinType::Kind::OCLImage3dRO:
4808 case clang::BuiltinType::Kind::OCLImage3dWO:
4809 case clang::BuiltinType::Kind::OCLImage3dRW:
4810 case clang::BuiltinType::Kind::OCLQueue:
4811 case clang::BuiltinType::Kind::OCLReserveID:
4812 case clang::BuiltinType::Kind::OCLSampler:
4813 case clang::BuiltinType::Kind::OMPArraySection:
4814 case clang::BuiltinType::Kind::OMPArrayShaping:
4815 case clang::BuiltinType::Kind::OMPIterator:
4816 case clang::BuiltinType::Kind::Overload:
4817 case clang::BuiltinType::Kind::PseudoObject:
4818 case clang::BuiltinType::Kind::UnknownAny:
4819 break;
4820
4821 case clang::BuiltinType::OCLIntelSubgroupAVCMcePayload:
4822 case clang::BuiltinType::OCLIntelSubgroupAVCImePayload:
4823 case clang::BuiltinType::OCLIntelSubgroupAVCRefPayload:
4824 case clang::BuiltinType::OCLIntelSubgroupAVCSicPayload:
4825 case clang::BuiltinType::OCLIntelSubgroupAVCMceResult:
4826 case clang::BuiltinType::OCLIntelSubgroupAVCImeResult:
4827 case clang::BuiltinType::OCLIntelSubgroupAVCRefResult:
4828 case clang::BuiltinType::OCLIntelSubgroupAVCSicResult:
4829 case clang::BuiltinType::OCLIntelSubgroupAVCImeResultSingleRefStreamout:
4830 case clang::BuiltinType::OCLIntelSubgroupAVCImeResultDualRefStreamout:
4831 case clang::BuiltinType::OCLIntelSubgroupAVCImeSingleRefStreamin:
4832 case clang::BuiltinType::OCLIntelSubgroupAVCImeDualRefStreamin:
4833 break;
4834
4835 // PowerPC -- Matrix Multiply Assist
4836 case clang::BuiltinType::VectorPair:
4837 case clang::BuiltinType::VectorQuad:
4838 break;
4839
4840 // ARM -- Scalable Vector Extension
4841 case clang::BuiltinType::SveBool:
4842 case clang::BuiltinType::SveInt8:
4843 case clang::BuiltinType::SveInt8x2:
4844 case clang::BuiltinType::SveInt8x3:
4845 case clang::BuiltinType::SveInt8x4:
4846 case clang::BuiltinType::SveInt16:
4847 case clang::BuiltinType::SveInt16x2:
4848 case clang::BuiltinType::SveInt16x3:
4849 case clang::BuiltinType::SveInt16x4:
4850 case clang::BuiltinType::SveInt32:
4851 case clang::BuiltinType::SveInt32x2:
4852 case clang::BuiltinType::SveInt32x3:
4853 case clang::BuiltinType::SveInt32x4:
4854 case clang::BuiltinType::SveInt64:
4855 case clang::BuiltinType::SveInt64x2:
4856 case clang::BuiltinType::SveInt64x3:
4857 case clang::BuiltinType::SveInt64x4:
4858 case clang::BuiltinType::SveUint8:
4859 case clang::BuiltinType::SveUint8x2:
4860 case clang::BuiltinType::SveUint8x3:
4861 case clang::BuiltinType::SveUint8x4:
4862 case clang::BuiltinType::SveUint16:
4863 case clang::BuiltinType::SveUint16x2:
4864 case clang::BuiltinType::SveUint16x3:
4865 case clang::BuiltinType::SveUint16x4:
4866 case clang::BuiltinType::SveUint32:
4867 case clang::BuiltinType::SveUint32x2:
4868 case clang::BuiltinType::SveUint32x3:
4869 case clang::BuiltinType::SveUint32x4:
4870 case clang::BuiltinType::SveUint64:
4871 case clang::BuiltinType::SveUint64x2:
4872 case clang::BuiltinType::SveUint64x3:
4873 case clang::BuiltinType::SveUint64x4:
4874 case clang::BuiltinType::SveFloat16:
4875 case clang::BuiltinType::SveBFloat16:
4876 case clang::BuiltinType::SveBFloat16x2:
4877 case clang::BuiltinType::SveBFloat16x3:
4878 case clang::BuiltinType::SveBFloat16x4:
4879 case clang::BuiltinType::SveFloat16x2:
4880 case clang::BuiltinType::SveFloat16x3:
4881 case clang::BuiltinType::SveFloat16x4:
4882 case clang::BuiltinType::SveFloat32:
4883 case clang::BuiltinType::SveFloat32x2:
4884 case clang::BuiltinType::SveFloat32x3:
4885 case clang::BuiltinType::SveFloat32x4:
4886 case clang::BuiltinType::SveFloat64:
4887 case clang::BuiltinType::SveFloat64x2:
4888 case clang::BuiltinType::SveFloat64x3:
4889 case clang::BuiltinType::SveFloat64x4:
4890 break;
4891
4892 case clang::BuiltinType::IncompleteMatrixIdx:
4893 break;
4894 }
4895 break;
4896 // All pointer types are represented as unsigned integer encodings. We may
4897 // nee to add a eEncodingPointer if we ever need to know the difference
4898 case clang::Type::ObjCObjectPointer:
4899 case clang::Type::BlockPointer:
4900 case clang::Type::Pointer:
4901 case clang::Type::LValueReference:
4902 case clang::Type::RValueReference:
4903 case clang::Type::MemberPointer:
4904 return lldb::eEncodingUint;
4905 case clang::Type::Complex: {
4906 lldb::Encoding encoding = lldb::eEncodingIEEE754;
4907 if (qual_type->isComplexType())
4908 encoding = lldb::eEncodingIEEE754;
4909 else {
4910 const clang::ComplexType *complex_type =
4911 qual_type->getAsComplexIntegerType();
4912 if (complex_type)
4913 encoding = GetType(complex_type->getElementType()).GetEncoding(count);
4914 else
4915 encoding = lldb::eEncodingSint;
4916 }
4917 count = 2;
4918 return encoding;
4919 }
4920
4921 case clang::Type::ObjCInterface:
4922 break;
4923 case clang::Type::Record:
4924 break;
4925 case clang::Type::Enum:
4926 return lldb::eEncodingSint;
4927 case clang::Type::DependentSizedArray:
4928 case clang::Type::DependentSizedExtVector:
4929 case clang::Type::UnresolvedUsing:
4930 case clang::Type::Attributed:
4931 case clang::Type::TemplateTypeParm:
4932 case clang::Type::SubstTemplateTypeParm:
4933 case clang::Type::SubstTemplateTypeParmPack:
4934 case clang::Type::InjectedClassName:
4935 case clang::Type::DependentName:
4936 case clang::Type::DependentTemplateSpecialization:
4937 case clang::Type::PackExpansion:
4938 case clang::Type::ObjCObject:
4939
4940 case clang::Type::TemplateSpecialization:
4941 case clang::Type::DeducedTemplateSpecialization:
4942 case clang::Type::Adjusted:
4943 case clang::Type::Pipe:
4944 break;
4945
4946 // pointer type decayed from an array or function type.
4947 case clang::Type::Decayed:
4948 break;
4949 case clang::Type::ObjCTypeParam:
4950 break;
4951
4952 case clang::Type::DependentAddressSpace:
4953 break;
4954 case clang::Type::MacroQualified:
4955 break;
4956
4957 case clang::Type::ConstantMatrix:
4958 case clang::Type::DependentSizedMatrix:
4959 break;
4960 }
4961 count = 0;
4962 return lldb::eEncodingInvalid;
4963}
4964
4965lldb::Format TypeSystemClang::GetFormat(lldb::opaque_compiler_type_t type) {
4966 if (!type)
4967 return lldb::eFormatDefault;
4968
4969 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
4970
4971 switch (qual_type->getTypeClass()) {
4972 case clang::Type::Atomic:
4973 case clang::Type::Auto:
4974 case clang::Type::Decltype:
4975 case clang::Type::Elaborated:
4976 case clang::Type::Paren:
4977 case clang::Type::Typedef:
4978 case clang::Type::TypeOf:
4979 case clang::Type::TypeOfExpr:
4980 llvm_unreachable("Handled in RemoveWrappingTypes!");
4981 case clang::Type::UnaryTransform:
4982 break;
4983
4984 case clang::Type::FunctionNoProto:
4985 case clang::Type::FunctionProto:
4986 break;
4987
4988 case clang::Type::IncompleteArray:
4989 case clang::Type::VariableArray:
4990 break;
4991
4992 case clang::Type::ConstantArray:
4993 return lldb::eFormatVoid; // no value
4994
4995 case clang::Type::DependentVector:
4996 case clang::Type::ExtVector:
4997 case clang::Type::Vector:
4998 break;
4999
5000 case clang::Type::ExtInt:
5001 case clang::Type::DependentExtInt:
5002 return qual_type->isUnsignedIntegerType() ? lldb::eFormatUnsigned
5003 : lldb::eFormatDecimal;
5004
5005 case clang::Type::Builtin:
5006 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
5007 case clang::BuiltinType::UnknownAny:
5008 case clang::BuiltinType::Void:
5009 case clang::BuiltinType::BoundMember:
5010 break;
5011
5012 case clang::BuiltinType::Bool:
5013 return lldb::eFormatBoolean;
5014 case clang::BuiltinType::Char_S:
5015 case clang::BuiltinType::SChar:
5016 case clang::BuiltinType::WChar_S:
5017 case clang::BuiltinType::Char_U:
5018 case clang::BuiltinType::UChar:
5019 case clang::BuiltinType::WChar_U:
5020 return lldb::eFormatChar;
5021 case clang::BuiltinType::Char16:
5022 return lldb::eFormatUnicode16;
5023 case clang::BuiltinType::Char32:
5024 return lldb::eFormatUnicode32;
5025 case clang::BuiltinType::UShort:
5026 return lldb::eFormatUnsigned;
5027 case clang::BuiltinType::Short:
5028 return lldb::eFormatDecimal;
5029 case clang::BuiltinType::UInt:
5030 return lldb::eFormatUnsigned;
5031 case clang::BuiltinType::Int:
5032 return lldb::eFormatDecimal;
5033 case clang::BuiltinType::ULong:
5034 return lldb::eFormatUnsigned;
5035 case clang::BuiltinType::Long:
5036 return lldb::eFormatDecimal;
5037 case clang::BuiltinType::ULongLong:
5038 return lldb::eFormatUnsigned;
5039 case clang::BuiltinType::LongLong:
5040 return lldb::eFormatDecimal;
5041 case clang::BuiltinType::UInt128:
5042 return lldb::eFormatUnsigned;
5043 case clang::BuiltinType::Int128:
5044 return lldb::eFormatDecimal;
5045 case clang::BuiltinType::Half:
5046 case clang::BuiltinType::Float:
5047 case clang::BuiltinType::Double:
5048 case clang::BuiltinType::LongDouble:
5049 return lldb::eFormatFloat;
5050 default:
5051 return lldb::eFormatHex;
5052 }
5053 break;
5054 case clang::Type::ObjCObjectPointer:
5055 return lldb::eFormatHex;
5056 case clang::Type::BlockPointer:
5057 return lldb::eFormatHex;
5058 case clang::Type::Pointer:
5059 return lldb::eFormatHex;
5060 case clang::Type::LValueReference:
5061 case clang::Type::RValueReference:
5062 return lldb::eFormatHex;
5063 case clang::Type::MemberPointer:
5064 break;
5065 case clang::Type::Complex: {
5066 if (qual_type->isComplexType())
5067 return lldb::eFormatComplex;
5068 else
5069 return lldb::eFormatComplexInteger;
5070 }
5071 case clang::Type::ObjCInterface:
5072 break;
5073 case clang::Type::Record:
5074 break;
5075 case clang::Type::Enum:
5076 return lldb::eFormatEnum;
5077 case clang::Type::DependentSizedArray:
5078 case clang::Type::DependentSizedExtVector:
5079 case clang::Type::UnresolvedUsing:
5080 case clang::Type::Attributed:
5081 case clang::Type::TemplateTypeParm:
5082 case clang::Type::SubstTemplateTypeParm:
5083 case clang::Type::SubstTemplateTypeParmPack:
5084 case clang::Type::InjectedClassName:
5085 case clang::Type::DependentName:
5086 case clang::Type::DependentTemplateSpecialization:
5087 case clang::Type::PackExpansion:
5088 case clang::Type::ObjCObject:
5089
5090 case clang::Type::TemplateSpecialization:
5091 case clang::Type::DeducedTemplateSpecialization:
5092 case clang::Type::Adjusted:
5093 case clang::Type::Pipe:
5094 break;
5095
5096 // pointer type decayed from an array or function type.
5097 case clang::Type::Decayed:
5098 break;
5099 case clang::Type::ObjCTypeParam:
5100 break;
5101
5102 case clang::Type::DependentAddressSpace:
5103 break;
5104 case clang::Type::MacroQualified:
5105 break;
5106
5107 // Matrix types we're not sure how to display yet.
5108 case clang::Type::ConstantMatrix:
5109 case clang::Type::DependentSizedMatrix:
5110 break;
5111 }
5112 // We don't know hot to display this type...
5113 return lldb::eFormatBytes;
5114}
5115
5116static bool ObjCDeclHasIVars(clang::ObjCInterfaceDecl *class_interface_decl,
5117 bool check_superclass) {
5118 while (class_interface_decl) {
5119 if (class_interface_decl->ivar_size() > 0)
5120 return true;
5121
5122 if (check_superclass)
5123 class_interface_decl = class_interface_decl->getSuperClass();
5124 else
5125 break;
5126 }
5127 return false;
5128}
5129
5130static Optional<SymbolFile::ArrayInfo>
5131GetDynamicArrayInfo(TypeSystemClang &ast, SymbolFile *sym_file,
5132 clang::QualType qual_type,
5133 const ExecutionContext *exe_ctx) {
5134 if (qual_type->isIncompleteArrayType())
5135 if (auto *metadata = ast.GetMetadata(qual_type.getTypePtr()))
5136 return sym_file->GetDynamicArrayInfoForUID(metadata->GetUserID(),
5137 exe_ctx);
5138 return llvm::None;
5139}
5140
5141uint32_t TypeSystemClang::GetNumChildren(lldb::opaque_compiler_type_t type,
5142 bool omit_empty_base_classes,
5143 const ExecutionContext *exe_ctx) {
5144 if (!type)
5145 return 0;
5146
5147 uint32_t num_children = 0;
5148 clang::QualType qual_type(RemoveWrappingTypes(GetQualType(type)));
5149 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5150 switch (type_class) {
5151 case clang::Type::Builtin:
5152 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
5153 case clang::BuiltinType::ObjCId: // child is Class
5154 case clang::BuiltinType::ObjCClass: // child is Class
5155 num_children = 1;
5156 break;
5157
5158 default:
5159 break;
5160 }
5161 break;
5162
5163 case clang::Type::Complex:
5164 return 0;
5165 case clang::Type::Record:
5166 if (GetCompleteQualType(&getASTContext(), qual_type)) {
5167 const clang::RecordType *record_type =
5168 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
5169 const clang::RecordDecl *record_decl = record_type->getDecl();
5170 assert(record_decl);
5171 const clang::CXXRecordDecl *cxx_record_decl =
5172 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
5173 if (cxx_record_decl) {
5174 if (omit_empty_base_classes) {
5175 // Check each base classes to see if it or any of its base classes
5176 // contain any fields. This can help limit the noise in variable
5177 // views by not having to show base classes that contain no members.
5178 clang::CXXRecordDecl::base_class_const_iterator base_class,
5179 base_class_end;
5180 for (base_class = cxx_record_decl->bases_begin(),
5181 base_class_end = cxx_record_decl->bases_end();
5182 base_class != base_class_end; ++base_class) {
5183 const clang::CXXRecordDecl *base_class_decl =
5184 llvm::cast<clang::CXXRecordDecl>(
5185 base_class->getType()
5186 ->getAs<clang::RecordType>()
5187 ->getDecl());
5188
5189 // Skip empty base classes
5190 if (!TypeSystemClang::RecordHasFields(base_class_decl))
5191 continue;
5192
5193 num_children++;
5194 }
5195 } else {
5196 // Include all base classes
5197 num_children += cxx_record_decl->getNumBases();
5198 }
5199 }
5200 clang::RecordDecl::field_iterator field, field_end;
5201 for (field = record_decl->field_begin(),
5202 field_end = record_decl->field_end();
5203 field != field_end; ++field)
5204 ++num_children;
5205 }
5206 break;
5207
5208 case clang::Type::ObjCObject:
5209 case clang::Type::ObjCInterface:
5210 if (GetCompleteQualType(&getASTContext(), qual_type)) {
5211 const clang::ObjCObjectType *objc_class_type =
5212 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
5213 assert(objc_class_type);
5214 if (objc_class_type) {
5215 clang::ObjCInterfaceDecl *class_interface_decl =
5216 objc_class_type->getInterface();
5217
5218 if (class_interface_decl) {
5219
5220 clang::ObjCInterfaceDecl *superclass_interface_decl =
5221 class_interface_decl->getSuperClass();
5222 if (superclass_interface_decl) {
5223 if (omit_empty_base_classes) {
5224 if (ObjCDeclHasIVars(superclass_interface_decl, true))
5225 ++num_children;
5226 } else
5227 ++num_children;
5228 }
5229
5230 num_children += class_interface_decl->ivar_size();
5231 }
5232 }
5233 }
5234 break;
5235
5236 case clang::Type::LValueReference:
5237 case clang::Type::RValueReference:
5238 case clang::Type::ObjCObjectPointer: {
5239 CompilerType pointee_clang_type(GetPointeeType(type));
5240
5241 uint32_t num_pointee_children = 0;
5242 if (pointee_clang_type.IsAggregateType())
5243 num_pointee_children =
5244 pointee_clang_type.GetNumChildren(omit_empty_base_classes, exe_ctx);
5245 // If this type points to a simple type, then it has 1 child
5246 if (num_pointee_children == 0)
5247 num_children = 1;
5248 else
5249 num_children = num_pointee_children;
5250 } break;
5251
5252 case clang::Type::Vector:
5253 case clang::Type::ExtVector:
5254 num_children =
5255 llvm::cast<clang::VectorType>(qual_type.getTypePtr())->getNumElements();
5256 break;
5257
5258 case clang::Type::ConstantArray:
5259 num_children = llvm::cast<clang::ConstantArrayType>(qual_type.getTypePtr())
5260 ->getSize()
5261 .getLimitedValue();
5262 break;
5263 case clang::Type::IncompleteArray:
5264 if (auto array_info =
5265 GetDynamicArrayInfo(*this, GetSymbolFile(), qual_type, exe_ctx))
5266 // Only 1-dimensional arrays are supported.
5267 num_children = array_info->element_orders.size()
5268 ? array_info->element_orders.back()
5269 : 0;
5270 break;
5271
5272 case clang::Type::Pointer: {
5273 const clang::PointerType *pointer_type =
5274 llvm::cast<clang::PointerType>(qual_type.getTypePtr());
5275 clang::QualType pointee_type(pointer_type->getPointeeType());
5276 CompilerType pointee_clang_type(GetType(pointee_type));
5277 uint32_t num_pointee_children = 0;
5278 if (pointee_clang_type.IsAggregateType())
5279 num_pointee_children =
5280 pointee_clang_type.GetNumChildren(omit_empty_base_classes, exe_ctx);
5281 if (num_pointee_children == 0) {
5282 // We have a pointer to a pointee type that claims it has no children. We
5283 // will want to look at
5284 num_children = GetNumPointeeChildren(pointee_type);
5285 } else
5286 num_children = num_pointee_children;
5287 } break;
5288
5289 default:
5290 break;
5291 }
5292 return num_children;
5293}
5294
5295CompilerType TypeSystemClang::GetBuiltinTypeByName(ConstString name) {
5296 return GetBasicType(GetBasicTypeEnumeration(name));
5297}
5298
5299lldb::BasicType
5300TypeSystemClang::GetBasicTypeEnumeration(lldb::opaque_compiler_type_t type) {
5301 if (type) {
5302 clang::QualType qual_type(GetQualType(type));
5303 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5304 if (type_class == clang::Type::Builtin) {
5305 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
5306 case clang::BuiltinType::Void:
5307 return eBasicTypeVoid;
5308 case clang::BuiltinType::Bool:
5309 return eBasicTypeBool;
5310 case clang::BuiltinType::Char_S:
5311 return eBasicTypeSignedChar;
5312 case clang::BuiltinType::Char_U:
5313 return eBasicTypeUnsignedChar;
5314 case clang::BuiltinType::Char16:
5315 return eBasicTypeChar16;
5316 case clang::BuiltinType::Char32:
5317 return eBasicTypeChar32;
5318 case clang::BuiltinType::UChar:
5319 return eBasicTypeUnsignedChar;
5320 case clang::BuiltinType::SChar:
5321 return eBasicTypeSignedChar;
5322 case clang::BuiltinType::WChar_S:
5323 return eBasicTypeSignedWChar;
5324 case clang::BuiltinType::WChar_U:
5325 return eBasicTypeUnsignedWChar;
5326 case clang::BuiltinType::Short:
5327 return eBasicTypeShort;
5328 case clang::BuiltinType::UShort:
5329 return eBasicTypeUnsignedShort;
5330 case clang::BuiltinType::Int:
5331 return eBasicTypeInt;
5332 case clang::BuiltinType::UInt:
5333 return eBasicTypeUnsignedInt;
5334 case clang::BuiltinType::Long:
5335 return eBasicTypeLong;
5336 case clang::BuiltinType::ULong:
5337 return eBasicTypeUnsignedLong;
5338 case clang::BuiltinType::LongLong:
5339 return eBasicTypeLongLong;
5340 case clang::BuiltinType::ULongLong:
5341 return eBasicTypeUnsignedLongLong;
5342 case clang::BuiltinType::Int128:
5343 return eBasicTypeInt128;
5344 case clang::BuiltinType::UInt128:
5345 return eBasicTypeUnsignedInt128;
5346
5347 case clang::BuiltinType::Half:
5348 return eBasicTypeHalf;
5349 case clang::BuiltinType::Float:
5350 return eBasicTypeFloat;
5351 case clang::BuiltinType::Double:
5352 return eBasicTypeDouble;
5353 case clang::BuiltinType::LongDouble:
5354 return eBasicTypeLongDouble;
5355
5356 case clang::BuiltinType::NullPtr:
5357 return eBasicTypeNullPtr;
5358 case clang::BuiltinType::ObjCId:
5359 return eBasicTypeObjCID;
5360 case clang::BuiltinType::ObjCClass:
5361 return eBasicTypeObjCClass;
5362 case clang::BuiltinType::ObjCSel:
5363 return eBasicTypeObjCSel;
5364 default:
5365 return eBasicTypeOther;
5366 }
5367 }
5368 }
5369 return eBasicTypeInvalid;
5370}
5371
5372void TypeSystemClang::ForEachEnumerator(
5373 lldb::opaque_compiler_type_t type,
5374 std::function<bool(const CompilerType &integer_type,
5375 ConstString name,
5376 const llvm::APSInt &value)> const &callback) {
5377 const clang::EnumType *enum_type =
5378 llvm::dyn_cast<clang::EnumType>(GetCanonicalQualType(type));
5379 if (enum_type) {
5380 const clang::EnumDecl *enum_decl = enum_type->getDecl();
5381 if (enum_decl) {
5382 CompilerType integer_type = GetType(enum_decl->getIntegerType());
5383
5384 clang::EnumDecl::enumerator_iterator enum_pos, enum_end_pos;
5385 for (enum_pos = enum_decl->enumerator_begin(),
5386 enum_end_pos = enum_decl->enumerator_end();
5387 enum_pos != enum_end_pos; ++enum_pos) {
5388 ConstString name(enum_pos->getNameAsString().c_str());
5389 if (!callback(integer_type, name, enum_pos->getInitVal()))
5390 break;
5391 }
5392 }
5393 }
5394}
5395
5396#pragma mark Aggregate Types
5397
5398uint32_t TypeSystemClang::GetNumFields(lldb::opaque_compiler_type_t type) {
5399 if (!type)
5400 return 0;
5401
5402 uint32_t count = 0;
5403 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
5404 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5405 switch (type_class) {
5406 case clang::Type::Record:
5407 if (GetCompleteType(type)) {
5408 const clang::RecordType *record_type =
5409 llvm::dyn_cast<clang::RecordType>(qual_type.getTypePtr());
5410 if (record_type) {
5411 clang::RecordDecl *record_decl = record_type->getDecl();
5412 if (record_decl) {
5413 uint32_t field_idx = 0;
5414 clang::RecordDecl::field_iterator field, field_end;
5415 for (field = record_decl->field_begin(),
5416 field_end = record_decl->field_end();
5417 field != field_end; ++field)
5418 ++field_idx;
5419 count = field_idx;
5420 }
5421 }
5422 }
5423 break;
5424
5425 case clang::Type::ObjCObjectPointer: {
5426 const clang::ObjCObjectPointerType *objc_class_type =
5427 qual_type->getAs<clang::ObjCObjectPointerType>();
5428 const clang::ObjCInterfaceType *objc_interface_type =
5429 objc_class_type->getInterfaceType();
5430 if (objc_interface_type &&
5431 GetCompleteType(static_cast<lldb::opaque_compiler_type_t>(
5432 const_cast<clang::ObjCInterfaceType *>(objc_interface_type)))) {
5433 clang::ObjCInterfaceDecl *class_interface_decl =
5434 objc_interface_type->getDecl();
5435 if (class_interface_decl) {
5436 count = class_interface_decl->ivar_size();
5437 }
5438 }
5439 break;
5440 }
5441
5442 case clang::Type::ObjCObject:
5443 case clang::Type::ObjCInterface:
5444 if (GetCompleteType(type)) {
5445 const clang::ObjCObjectType *objc_class_type =
5446 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
5447 if (objc_class_type) {
5448 clang::ObjCInterfaceDecl *class_interface_decl =
5449 objc_class_type->getInterface();
5450
5451 if (class_interface_decl)
5452 count = class_interface_decl->ivar_size();
5453 }
5454 }
5455 break;
5456
5457 default:
5458 break;
5459 }
5460 return count;
5461}
5462
5463static lldb::opaque_compiler_type_t
5464GetObjCFieldAtIndex(clang::ASTContext *ast,
5465 clang::ObjCInterfaceDecl *class_interface_decl, size_t idx,
5466 std::string &name, uint64_t *bit_offset_ptr,
5467 uint32_t *bitfield_bit_size_ptr, bool *is_bitfield_ptr) {
5468 if (class_interface_decl) {
5469 if (idx < (class_interface_decl->ivar_size())) {
5470 clang::ObjCInterfaceDecl::ivar_iterator ivar_pos,
5471 ivar_end = class_interface_decl->ivar_end();
5472 uint32_t ivar_idx = 0;
5473
5474 for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end;
5475 ++ivar_pos, ++ivar_idx) {
5476 if (ivar_idx == idx) {
5477 const clang::ObjCIvarDecl *ivar_decl = *ivar_pos;
5478
5479 clang::QualType ivar_qual_type(ivar_decl->getType());
5480
5481 name.assign(ivar_decl->getNameAsString());
5482
5483 if (bit_offset_ptr) {
5484 const clang::ASTRecordLayout &interface_layout =
5485 ast->getASTObjCInterfaceLayout(class_interface_decl);
5486 *bit_offset_ptr = interface_layout.getFieldOffset(ivar_idx);
5487 }
5488
5489 const bool is_bitfield = ivar_pos->isBitField();
5490
5491 if (bitfield_bit_size_ptr) {
5492 *bitfield_bit_size_ptr = 0;
5493
5494 if (is_bitfield && ast) {
5495 clang::Expr *bitfield_bit_size_expr = ivar_pos->getBitWidth();
5496 clang::Expr::EvalResult result;
5497 if (bitfield_bit_size_expr &&
5498 bitfield_bit_size_expr->EvaluateAsInt(result, *ast)) {
5499 llvm::APSInt bitfield_apsint = result.Val.getInt();
5500 *bitfield_bit_size_ptr = bitfield_apsint.getLimitedValue();
5501 }
5502 }
5503 }
5504 if (is_bitfield_ptr)
5505 *is_bitfield_ptr = is_bitfield;
5506
5507 return ivar_qual_type.getAsOpaquePtr();
5508 }
5509 }
5510 }
5511 }
5512 return nullptr;
5513}
5514
5515CompilerType TypeSystemClang::GetFieldAtIndex(lldb::opaque_compiler_type_t type,
5516 size_t idx, std::string &name,
5517 uint64_t *bit_offset_ptr,
5518 uint32_t *bitfield_bit_size_ptr,
5519 bool *is_bitfield_ptr) {
5520 if (!type)
5521 return CompilerType();
5522
5523 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
5524 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5525 switch (type_class) {
5526 case clang::Type::Record:
5527 if (GetCompleteType(type)) {
5528 const clang::RecordType *record_type =
5529 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
5530 const clang::RecordDecl *record_decl = record_type->getDecl();
5531 uint32_t field_idx = 0;
5532 clang::RecordDecl::field_iterator field, field_end;
5533 for (field = record_decl->field_begin(),
5534 field_end = record_decl->field_end();
5535 field != field_end; ++field, ++field_idx) {
5536 if (idx == field_idx) {
5537 // Print the member type if requested
5538 // Print the member name and equal sign
5539 name.assign(field->getNameAsString());
5540
5541 // Figure out the type byte size (field_type_info.first) and
5542 // alignment (field_type_info.second) from the AST context.
5543 if (bit_offset_ptr) {
5544 const clang::ASTRecordLayout &record_layout =
5545 getASTContext().getASTRecordLayout(record_decl);
5546 *bit_offset_ptr = record_layout.getFieldOffset(field_idx);
5547 }
5548
5549 const bool is_bitfield = field->isBitField();
5550
5551 if (bitfield_bit_size_ptr) {
5552 *bitfield_bit_size_ptr = 0;
5553
5554 if (is_bitfield) {
5555 clang::Expr *bitfield_bit_size_expr = field->getBitWidth();
5556 clang::Expr::EvalResult result;
5557 if (bitfield_bit_size_expr &&
5558 bitfield_bit_size_expr->EvaluateAsInt(result,
5559 getASTContext())) {
5560 llvm::APSInt bitfield_apsint = result.Val.getInt();
5561 *bitfield_bit_size_ptr = bitfield_apsint.getLimitedValue();
5562 }
5563 }
5564 }
5565 if (is_bitfield_ptr)
5566 *is_bitfield_ptr = is_bitfield;
5567
5568 return GetType(field->getType());
5569 }
5570 }
5571 }
5572 break;
5573
5574 case clang::Type::ObjCObjectPointer: {
5575 const clang::ObjCObjectPointerType *objc_class_type =
5576 qual_type->getAs<clang::ObjCObjectPointerType>();
5577 const clang::ObjCInterfaceType *objc_interface_type =
5578 objc_class_type->getInterfaceType();
5579 if (objc_interface_type &&
5580 GetCompleteType(static_cast<lldb::opaque_compiler_type_t>(
5581 const_cast<clang::ObjCInterfaceType *>(objc_interface_type)))) {
5582 clang::ObjCInterfaceDecl *class_interface_decl =
5583 objc_interface_type->getDecl();
5584 if (class_interface_decl) {
5585 return CompilerType(
5586 this, GetObjCFieldAtIndex(&getASTContext(), class_interface_decl,
5587 idx, name, bit_offset_ptr,
5588 bitfield_bit_size_ptr, is_bitfield_ptr));
5589 }
5590 }
5591 break;
5592 }
5593
5594 case clang::Type::ObjCObject:
5595 case clang::Type::ObjCInterface:
5596 if (GetCompleteType(type)) {
5597 const clang::ObjCObjectType *objc_class_type =
5598 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
5599 assert(objc_class_type);
5600 if (objc_class_type) {
5601 clang::ObjCInterfaceDecl *class_interface_decl =
5602 objc_class_type->getInterface();
5603 return CompilerType(
5604 this, GetObjCFieldAtIndex(&getASTContext(), class_interface_decl,
5605 idx, name, bit_offset_ptr,
5606 bitfield_bit_size_ptr, is_bitfield_ptr));
5607 }
5608 }
5609 break;
5610
5611 default:
5612 break;
5613 }
5614 return CompilerType();
5615}
5616
5617uint32_t
5618TypeSystemClang::GetNumDirectBaseClasses(lldb::opaque_compiler_type_t type) {
5619 uint32_t count = 0;
5620 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
5621 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5622 switch (type_class) {
5623 case clang::Type::Record:
5624 if (GetCompleteType(type)) {
5625 const clang::CXXRecordDecl *cxx_record_decl =
5626 qual_type->getAsCXXRecordDecl();
5627 if (cxx_record_decl)
5628 count = cxx_record_decl->getNumBases();
5629 }
5630 break;
5631
5632 case clang::Type::ObjCObjectPointer:
5633 count = GetPointeeType(type).GetNumDirectBaseClasses();
5634 break;
5635
5636 case clang::Type::ObjCObject:
5637 if (GetCompleteType(type)) {
5638 const clang::ObjCObjectType *objc_class_type =
5639 qual_type->getAsObjCQualifiedInterfaceType();
5640 if (objc_class_type) {
5641 clang::ObjCInterfaceDecl *class_interface_decl =
5642 objc_class_type->getInterface();
5643
5644 if (class_interface_decl && class_interface_decl->getSuperClass())
5645 count = 1;
5646 }
5647 }
5648 break;
5649 case clang::Type::ObjCInterface:
5650 if (GetCompleteType(type)) {
5651 const clang::ObjCInterfaceType *objc_interface_type =
5652 qual_type->getAs<clang::ObjCInterfaceType>();
5653 if (objc_interface_type) {
5654 clang::ObjCInterfaceDecl *class_interface_decl =
5655 objc_interface_type->getInterface();
5656
5657 if (class_interface_decl && class_interface_decl->getSuperClass())
5658 count = 1;
5659 }
5660 }
5661 break;
5662
5663 default:
5664 break;
5665 }
5666 return count;
5667}
5668
5669uint32_t
5670TypeSystemClang::GetNumVirtualBaseClasses(lldb::opaque_compiler_type_t type) {
5671 uint32_t count = 0;
5672 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
5673 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5674 switch (type_class) {
5675 case clang::Type::Record:
5676 if (GetCompleteType(type)) {
5677 const clang::CXXRecordDecl *cxx_record_decl =
5678 qual_type->getAsCXXRecordDecl();
5679 if (cxx_record_decl)
5680 count = cxx_record_decl->getNumVBases();
5681 }
5682 break;
5683
5684 default:
5685 break;
5686 }
5687 return count;
5688}
5689
5690CompilerType TypeSystemClang::GetDirectBaseClassAtIndex(
5691 lldb::opaque_compiler_type_t type, size_t idx, uint32_t *bit_offset_ptr) {
5692 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
5693 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5694 switch (type_class) {
5695 case clang::Type::Record:
5696 if (GetCompleteType(type)) {
5697 const clang::CXXRecordDecl *cxx_record_decl =
5698 qual_type->getAsCXXRecordDecl();
5699 if (cxx_record_decl) {
5700 uint32_t curr_idx = 0;
5701 clang::CXXRecordDecl::base_class_const_iterator base_class,
5702 base_class_end;
5703 for (base_class = cxx_record_decl->bases_begin(),
5704 base_class_end = cxx_record_decl->bases_end();
5705 base_class != base_class_end; ++base_class, ++curr_idx) {
5706 if (curr_idx == idx) {
5707 if (bit_offset_ptr) {
5708 const clang::ASTRecordLayout &record_layout =
5709 getASTContext().getASTRecordLayout(cxx_record_decl);
5710 const clang::CXXRecordDecl *base_class_decl =
5711 llvm::cast<clang::CXXRecordDecl>(
5712 base_class->getType()
5713 ->getAs<clang::RecordType>()
5714 ->getDecl());
5715 if (base_class->isVirtual())
5716 *bit_offset_ptr =
5717 record_layout.getVBaseClassOffset(base_class_decl)
5718 .getQuantity() *
5719 8;
5720 else
5721 *bit_offset_ptr =
5722 record_layout.getBaseClassOffset(base_class_decl)
5723 .getQuantity() *
5724 8;
5725 }
5726 return GetType(base_class->getType());
5727 }
5728 }
5729 }
5730 }
5731 break;
5732
5733 case clang::Type::ObjCObjectPointer:
5734 return GetPointeeType(type).GetDirectBaseClassAtIndex(idx, bit_offset_ptr);
5735
5736 case clang::Type::ObjCObject:
5737 if (idx == 0 && GetCompleteType(type)) {
5738 const clang::ObjCObjectType *objc_class_type =
5739 qual_type->getAsObjCQualifiedInterfaceType();
5740 if (objc_class_type) {
5741 clang::ObjCInterfaceDecl *class_interface_decl =
5742 objc_class_type->getInterface();
5743
5744 if (class_interface_decl) {
5745 clang::ObjCInterfaceDecl *superclass_interface_decl =
5746 class_interface_decl->getSuperClass();
5747 if (superclass_interface_decl) {
5748 if (bit_offset_ptr)
5749 *bit_offset_ptr = 0;
5750 return GetType(getASTContext().getObjCInterfaceType(
5751 superclass_interface_decl));
5752 }
5753 }
5754 }
5755 }
5756 break;
5757 case clang::Type::ObjCInterface:
5758 if (idx == 0 && GetCompleteType(type)) {
5759 const clang::ObjCObjectType *objc_interface_type =
5760 qual_type->getAs<clang::ObjCInterfaceType>();
5761 if (objc_interface_type) {
5762 clang::ObjCInterfaceDecl *class_interface_decl =
5763 objc_interface_type->getInterface();
5764
5765 if (class_interface_decl) {
5766 clang::ObjCInterfaceDecl *superclass_interface_decl =
5767 class_interface_decl->getSuperClass();
5768 if (superclass_interface_decl) {
5769 if (bit_offset_ptr)
5770 *bit_offset_ptr = 0;
5771 return GetType(getASTContext().getObjCInterfaceType(
5772 superclass_interface_decl));
5773 }
5774 }
5775 }
5776 }
5777 break;
5778
5779 default:
5780 break;
5781 }
5782 return CompilerType();
5783}
5784
5785CompilerType TypeSystemClang::GetVirtualBaseClassAtIndex(
5786 lldb::opaque_compiler_type_t type, size_t idx, uint32_t *bit_offset_ptr) {
5787 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
5788 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5789 switch (type_class) {
5790 case clang::Type::Record:
5791 if (GetCompleteType(type)) {
5792 const clang::CXXRecordDecl *cxx_record_decl =
5793 qual_type->getAsCXXRecordDecl();
5794 if (cxx_record_decl) {
5795 uint32_t curr_idx = 0;
5796 clang::CXXRecordDecl::base_class_const_iterator base_class,
5797 base_class_end;
5798 for (base_class = cxx_record_decl->vbases_begin(),
5799 base_class_end = cxx_record_decl->vbases_end();
5800 base_class != base_class_end; ++base_class, ++curr_idx) {
5801 if (curr_idx == idx) {
5802 if (bit_offset_ptr) {
5803 const clang::ASTRecordLayout &record_layout =
5804 getASTContext().getASTRecordLayout(cxx_record_decl);
5805 const clang::CXXRecordDecl *base_class_decl =
5806 llvm::cast<clang::CXXRecordDecl>(
5807 base_class->getType()
5808 ->getAs<clang::RecordType>()
5809 ->getDecl());
5810 *bit_offset_ptr =
5811 record_layout.getVBaseClassOffset(base_class_decl)
5812 .getQuantity() *
5813 8;
5814 }
5815 return GetType(base_class->getType());
5816 }
5817 }
5818 }
5819 }
5820 break;
5821
5822 default:
5823 break;
5824 }
5825 return CompilerType();
5826}
5827
5828// If a pointer to a pointee type (the clang_type arg) says that it has no
5829// children, then we either need to trust it, or override it and return a
5830// different result. For example, an "int *" has one child that is an integer,
5831// but a function pointer doesn't have any children. Likewise if a Record type
5832// claims it has no children, then there really is nothing to show.
5833uint32_t TypeSystemClang::GetNumPointeeChildren(clang::QualType type) {
5834 if (type.isNull())
5835 return 0;
5836
5837 clang::QualType qual_type = RemoveWrappingTypes(type.getCanonicalType());
5838 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
5839 switch (type_class) {
5840 case clang::Type::Builtin:
5841 switch (llvm::cast<clang::BuiltinType>(qual_type)->getKind()) {
5842 case clang::BuiltinType::UnknownAny:
5843 case clang::BuiltinType::Void:
5844 case clang::BuiltinType::NullPtr:
5845 case clang::BuiltinType::OCLEvent:
5846 case clang::BuiltinType::OCLImage1dRO:
5847 case clang::BuiltinType::OCLImage1dWO:
5848 case clang::BuiltinType::OCLImage1dRW:
5849 case clang::BuiltinType::OCLImage1dArrayRO:
5850 case clang::BuiltinType::OCLImage1dArrayWO:
5851 case clang::BuiltinType::OCLImage1dArrayRW:
5852 case clang::BuiltinType::OCLImage1dBufferRO:
5853 case clang::BuiltinType::OCLImage1dBufferWO:
5854 case clang::BuiltinType::OCLImage1dBufferRW:
5855 case clang::BuiltinType::OCLImage2dRO:
5856 case clang::BuiltinType::OCLImage2dWO:
5857 case clang::BuiltinType::OCLImage2dRW:
5858 case clang::BuiltinType::OCLImage2dArrayRO:
5859 case clang::BuiltinType::OCLImage2dArrayWO:
5860 case clang::BuiltinType::OCLImage2dArrayRW:
5861 case clang::BuiltinType::OCLImage3dRO:
5862 case clang::BuiltinType::OCLImage3dWO:
5863 case clang::BuiltinType::OCLImage3dRW:
5864 case clang::BuiltinType::OCLSampler:
5865 return 0;
5866 case clang::BuiltinType::Bool:
5867 case clang::BuiltinType::Char_U:
5868 case clang::BuiltinType::UChar:
5869 case clang::BuiltinType::WChar_U:
5870 case clang::BuiltinType::Char16:
5871 case clang::BuiltinType::Char32:
5872 case clang::BuiltinType::UShort:
5873 case clang::BuiltinType::UInt:
5874 case clang::BuiltinType::ULong:
5875 case clang::BuiltinType::ULongLong:
5876 case clang::BuiltinType::UInt128:
5877 case clang::BuiltinType::Char_S:
5878 case clang::BuiltinType::SChar:
5879 case clang::BuiltinType::WChar_S:
5880 case clang::BuiltinType::Short:
5881 case clang::BuiltinType::Int:
5882 case clang::BuiltinType::Long:
5883 case clang::BuiltinType::LongLong:
5884 case clang::BuiltinType::Int128:
5885 case clang::BuiltinType::Float:
5886 case clang::BuiltinType::Double:
5887 case clang::BuiltinType::LongDouble:
5888 case clang::BuiltinType::Dependent:
5889 case clang::BuiltinType::Overload:
5890 case clang::BuiltinType::ObjCId:
5891 case clang::BuiltinType::ObjCClass:
5892 case clang::BuiltinType::ObjCSel:
5893 case clang::BuiltinType::BoundMember:
5894 case clang::BuiltinType::Half:
5895 case clang::BuiltinType::ARCUnbridgedCast:
5896 case clang::BuiltinType::PseudoObject:
5897 case clang::BuiltinType::BuiltinFn:
5898 case clang::BuiltinType::OMPArraySection:
5899 return 1;
5900 default:
5901 return 0;
5902 }
5903 break;
5904
5905 case clang::Type::Complex:
5906 return 1;
5907 case clang::Type::Pointer:
5908 return 1;
5909 case clang::Type::BlockPointer:
5910 return 0; // If block pointers don't have debug info, then no children for
5911 // them
5912 case clang::Type::LValueReference:
5913 return 1;
5914 case clang::Type::RValueReference:
5915 return 1;
5916 case clang::Type::MemberPointer:
5917 return 0;
5918 case clang::Type::ConstantArray:
5919 return 0;
5920 case clang::Type::IncompleteArray:
5921 return 0;
5922 case clang::Type::VariableArray:
5923 return 0;
5924 case clang::Type::DependentSizedArray:
5925 return 0;
5926 case clang::Type::DependentSizedExtVector:
5927 return 0;
5928 case clang::Type::Vector:
5929 return 0;
5930 case clang::Type::ExtVector:
5931 return 0;
5932 case clang::Type::FunctionProto:
5933 return 0; // When we function pointers, they have no children...
5934 case clang::Type::FunctionNoProto:
5935 return 0; // When we function pointers, they have no children...
5936 case clang::Type::UnresolvedUsing:
5937 return 0;
5938 case clang::Type::Record:
5939 return 0;
5940 case clang::Type::Enum:
5941 return 1;
5942 case clang::Type::TemplateTypeParm:
5943 return 1;
5944 case clang::Type::SubstTemplateTypeParm:
5945 return 1;
5946 case clang::Type::TemplateSpecialization:
5947 return 1;
5948 case clang::Type::InjectedClassName:
5949 return 0;
5950 case clang::Type::DependentName:
5951 return 1;
5952 case clang::Type::DependentTemplateSpecialization:
5953 return 1;
5954 case clang::Type::ObjCObject:
5955 return 0;
5956 case clang::Type::ObjCInterface:
5957 return 0;
5958 case clang::Type::ObjCObjectPointer:
5959 return 1;
5960 default:
5961 break;
5962 }
5963 return 0;
5964}
5965
5966CompilerType TypeSystemClang::GetChildCompilerTypeAtIndex(
5967 lldb::opaque_compiler_type_t type, ExecutionContext *exe_ctx, size_t idx,
5968 bool transparent_pointers, bool omit_empty_base_classes,
5969 bool ignore_array_bounds, std::string &child_name,
5970 uint32_t &child_byte_size, int32_t &child_byte_offset,
5971 uint32_t &child_bitfield_bit_size, uint32_t &child_bitfield_bit_offset,
5972 bool &child_is_base_class, bool &child_is_deref_of_parent,
5973 ValueObject *valobj, uint64_t &language_flags) {
5974 if (!type)
5975 return CompilerType();
5976
5977 auto get_exe_scope = [&exe_ctx]() {
5978 return exe_ctx ? exe_ctx->GetBestExecutionContextScope() : nullptr;
5979 };
5980
5981 clang::QualType parent_qual_type(
5982 RemoveWrappingTypes(GetCanonicalQualType(type)));
5983 const clang::Type::TypeClass parent_type_class =
5984 parent_qual_type->getTypeClass();
5985 child_bitfield_bit_size = 0;
5986 child_bitfield_bit_offset = 0;
5987 child_is_base_class = false;
5988 language_flags = 0;
5989
5990 const bool idx_is_valid =
5991 idx < GetNumChildren(type, omit_empty_base_classes, exe_ctx);
5992 int32_t bit_offset;
5993 switch (parent_type_class) {
5994 case clang::Type::Builtin:
5995 if (idx_is_valid) {
5996 switch (llvm::cast<clang::BuiltinType>(parent_qual_type)->getKind()) {
5997 case clang::BuiltinType::ObjCId:
5998 case clang::BuiltinType::ObjCClass:
5999 child_name = "isa";
6000 child_byte_size =
6001 getASTContext().getTypeSize(getASTContext().ObjCBuiltinClassTy) /
6002 CHAR_BIT;
6003 return GetType(getASTContext().ObjCBuiltinClassTy);
6004
6005 default:
6006 break;
6007 }
6008 }
6009 break;
6010
6011 case clang::Type::Record:
6012 if (idx_is_valid && GetCompleteType(type)) {
6013 const clang::RecordType *record_type =
6014 llvm::cast<clang::RecordType>(parent_qual_type.getTypePtr());
6015 const clang::RecordDecl *record_decl = record_type->getDecl();
6016 assert(record_decl);
6017 const clang::ASTRecordLayout &record_layout =
6018 getASTContext().getASTRecordLayout(record_decl);
6019 uint32_t child_idx = 0;
6020
6021 const clang::CXXRecordDecl *cxx_record_decl =
6022 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
6023 if (cxx_record_decl) {
6024 // We might have base classes to print out first
6025 clang::CXXRecordDecl::base_class_const_iterator base_class,
6026 base_class_end;
6027 for (base_class = cxx_record_decl->bases_begin(),
6028 base_class_end = cxx_record_decl->bases_end();
6029 base_class != base_class_end; ++base_class) {
6030 const clang::CXXRecordDecl *base_class_decl = nullptr;
6031
6032 // Skip empty base classes
6033 if (omit_empty_base_classes) {
6034 base_class_decl = llvm::cast<clang::CXXRecordDecl>(
6035 base_class->getType()->getAs<clang::RecordType>()->getDecl());
6036 if (!TypeSystemClang::RecordHasFields(base_class_decl))
6037 continue;
6038 }
6039
6040 if (idx == child_idx) {
6041 if (base_class_decl == nullptr)
6042 base_class_decl = llvm::cast<clang::CXXRecordDecl>(
6043 base_class->getType()->getAs<clang::RecordType>()->getDecl());
6044
6045 if (base_class->isVirtual()) {
6046 bool handled = false;
6047 if (valobj) {
6048 clang::VTableContextBase *vtable_ctx =
6049 getASTContext().getVTableContext();
6050 if (vtable_ctx)
6051 handled = GetVBaseBitOffset(*vtable_ctx, *valobj,
6052 record_layout, cxx_record_decl,
6053 base_class_decl, bit_offset);
6054 }
6055 if (!handled)
6056 bit_offset = record_layout.getVBaseClassOffset(base_class_decl)
6057 .getQuantity() *
6058 8;
6059 } else
6060 bit_offset = record_layout.getBaseClassOffset(base_class_decl)
6061 .getQuantity() *
6062 8;
6063
6064 // Base classes should be a multiple of 8 bits in size
6065 child_byte_offset = bit_offset / 8;
6066 CompilerType base_class_clang_type = GetType(base_class->getType());
6067 child_name = base_class_clang_type.GetTypeName().AsCString("");
6068 Optional<uint64_t> size =
6069 base_class_clang_type.GetBitSize(get_exe_scope());
6070 if (!size)
6071 return {};
6072 uint64_t base_class_clang_type_bit_size = *size;
6073
6074 // Base classes bit sizes should be a multiple of 8 bits in size
6075 assert(base_class_clang_type_bit_size % 8 == 0);
6076 child_byte_size = base_class_clang_type_bit_size / 8;
6077 child_is_base_class = true;
6078 return base_class_clang_type;
6079 }
6080 // We don't increment the child index in the for loop since we might
6081 // be skipping empty base classes
6082 ++child_idx;
6083 }
6084 }
6085 // Make sure index is in range...
6086 uint32_t field_idx = 0;
6087 clang::RecordDecl::field_iterator field, field_end;
6088 for (field = record_decl->field_begin(),
6089 field_end = record_decl->field_end();
6090 field != field_end; ++field, ++field_idx, ++child_idx) {
6091 if (idx == child_idx) {
6092 // Print the member type if requested
6093 // Print the member name and equal sign
6094 child_name.assign(field->getNameAsString());
6095
6096 // Figure out the type byte size (field_type_info.first) and
6097 // alignment (field_type_info.second) from the AST context.
6098 CompilerType field_clang_type = GetType(field->getType());
6099 assert(field_idx < record_layout.getFieldCount());
6100 Optional<uint64_t> size =
6101 field_clang_type.GetByteSize(get_exe_scope());
6102 if (!size)
6103 return {};
6104 child_byte_size = *size;
6105 const uint32_t child_bit_size = child_byte_size * 8;
6106
6107 // Figure out the field offset within the current struct/union/class
6108 // type
6109 bit_offset = record_layout.getFieldOffset(field_idx);
6110 if (FieldIsBitfield(*field, child_bitfield_bit_size)) {
6111 child_bitfield_bit_offset = bit_offset % child_bit_size;
6112 const uint32_t child_bit_offset =
6113 bit_offset - child_bitfield_bit_offset;
6114 child_byte_offset = child_bit_offset / 8;
6115 } else {
6116 child_byte_offset = bit_offset / 8;
6117 }
6118
6119 return field_clang_type;
6120 }
6121 }
6122 }
6123 break;
6124
6125 case clang::Type::ObjCObject:
6126 case clang::Type::ObjCInterface:
6127 if (idx_is_valid && GetCompleteType(type)) {
6128 const clang::ObjCObjectType *objc_class_type =
6129 llvm::dyn_cast<clang::ObjCObjectType>(parent_qual_type.getTypePtr());
6130 assert(objc_class_type);
6131 if (objc_class_type) {
6132 uint32_t child_idx = 0;
6133 clang::ObjCInterfaceDecl *class_interface_decl =
6134 objc_class_type->getInterface();
6135
6136 if (class_interface_decl) {
6137
6138 const clang::ASTRecordLayout &interface_layout =
6139 getASTContext().getASTObjCInterfaceLayout(class_interface_decl);
6140 clang::ObjCInterfaceDecl *superclass_interface_decl =
6141 class_interface_decl->getSuperClass();
6142 if (superclass_interface_decl) {
6143 if (omit_empty_base_classes) {
6144 CompilerType base_class_clang_type =
6145 GetType(getASTContext().getObjCInterfaceType(
6146 superclass_interface_decl));
6147 if (base_class_clang_type.GetNumChildren(omit_empty_base_classes,
6148 exe_ctx) > 0) {
6149 if (idx == 0) {
6150 clang::QualType ivar_qual_type(
6151 getASTContext().getObjCInterfaceType(
6152 superclass_interface_decl));
6153
6154 child_name.assign(
6155 superclass_interface_decl->getNameAsString());
6156
6157 clang::TypeInfo ivar_type_info =
6158 getASTContext().getTypeInfo(ivar_qual_type.getTypePtr());
6159
6160 child_byte_size = ivar_type_info.Width / 8;
6161 child_byte_offset = 0;
6162 child_is_base_class = true;
6163
6164 return GetType(ivar_qual_type);
6165 }
6166
6167 ++child_idx;
6168 }
6169 } else
6170 ++child_idx;
6171 }
6172
6173 const uint32_t superclass_idx = child_idx;
6174
6175 if (idx < (child_idx + class_interface_decl->ivar_size())) {
6176 clang::ObjCInterfaceDecl::ivar_iterator ivar_pos,
6177 ivar_end = class_interface_decl->ivar_end();
6178
6179 for (ivar_pos = class_interface_decl->ivar_begin();
6180 ivar_pos != ivar_end; ++ivar_pos) {
6181 if (child_idx == idx) {
6182 clang::ObjCIvarDecl *ivar_decl = *ivar_pos;
6183
6184 clang::QualType ivar_qual_type(ivar_decl->getType());
6185
6186 child_name.assign(ivar_decl->getNameAsString());
6187
6188 clang::TypeInfo ivar_type_info =
6189 getASTContext().getTypeInfo(ivar_qual_type.getTypePtr());
6190
6191 child_byte_size = ivar_type_info.Width / 8;
6192
6193 // Figure out the field offset within the current
6194 // struct/union/class type For ObjC objects, we can't trust the
6195 // bit offset we get from the Clang AST, since that doesn't
6196 // account for the space taken up by unbacked properties, or
6197 // from the changing size of base classes that are newer than
6198 // this class. So if we have a process around that we can ask
6199 // about this object, do so.
6200 child_byte_offset = LLDB_INVALID_IVAR_OFFSET;
6201 Process *process = nullptr;
6202 if (exe_ctx)
6203 process = exe_ctx->GetProcessPtr();
6204 if (process) {
6205 ObjCLanguageRuntime *objc_runtime =
6206 ObjCLanguageRuntime::Get(*process);
6207 if (objc_runtime != nullptr) {
6208 CompilerType parent_ast_type = GetType(parent_qual_type);
6209 child_byte_offset = objc_runtime->GetByteOffsetForIvar(
6210 parent_ast_type, ivar_decl->getNameAsString().c_str());
6211 }
6212 }
6213
6214 // Setting this to INT32_MAX to make sure we don't compute it
6215 // twice...
6216 bit_offset = INT32_MAX;
6217
6218 if (child_byte_offset ==
6219 static_cast<int32_t>(LLDB_INVALID_IVAR_OFFSET)) {
6220 bit_offset = interface_layout.getFieldOffset(child_idx -
6221 superclass_idx);
6222 child_byte_offset = bit_offset / 8;
6223 }
6224
6225 // Note, the ObjC Ivar Byte offset is just that, it doesn't
6226 // account for the bit offset of a bitfield within its
6227 // containing object. So regardless of where we get the byte
6228 // offset from, we still need to get the bit offset for
6229 // bitfields from the layout.
6230
6231 if (FieldIsBitfield(ivar_decl, child_bitfield_bit_size)) {
6232 if (bit_offset == INT32_MAX)
6233 bit_offset = interface_layout.getFieldOffset(
6234 child_idx - superclass_idx);
6235
6236 child_bitfield_bit_offset = bit_offset % 8;
6237 }
6238 return GetType(ivar_qual_type);
6239 }
6240 ++child_idx;
6241 }
6242 }
6243 }
6244 }
6245 }
6246 break;
6247
6248 case clang::Type::ObjCObjectPointer:
6249 if (idx_is_valid) {
6250 CompilerType pointee_clang_type(GetPointeeType(type));
6251
6252 if (transparent_pointers && pointee_clang_type.IsAggregateType()) {
6253 child_is_deref_of_parent = false;
6254 bool tmp_child_is_deref_of_parent = false;
6255 return pointee_clang_type.GetChildCompilerTypeAtIndex(
6256 exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
6257 ignore_array_bounds, child_name, child_byte_size, child_byte_offset,
6258 child_bitfield_bit_size, child_bitfield_bit_offset,
6259 child_is_base_class, tmp_child_is_deref_of_parent, valobj,
6260 language_flags);
6261 } else {
6262 child_is_deref_of_parent = true;
6263 const char *parent_name =
6264 valobj ? valobj->GetName().GetCString() : nullptr;
6265 if (parent_name) {
6266 child_name.assign(1, '*');
6267 child_name += parent_name;
6268 }
6269
6270 // We have a pointer to an simple type
6271 if (idx == 0 && pointee_clang_type.GetCompleteType()) {
6272 if (Optional<uint64_t> size =
6273 pointee_clang_type.GetByteSize(get_exe_scope())) {
6274 child_byte_size = *size;
6275 child_byte_offset = 0;
6276 return pointee_clang_type;
6277 }
6278 }
6279 }
6280 }
6281 break;
6282
6283 case clang::Type::Vector:
6284 case clang::Type::ExtVector:
6285 if (idx_is_valid) {
6286 const clang::VectorType *array =
6287 llvm::cast<clang::VectorType>(parent_qual_type.getTypePtr());
6288 if (array) {
6289 CompilerType element_type = GetType(array->getElementType());
6290 if (element_type.GetCompleteType()) {
6291 char element_name[64];
6292 ::snprintf(element_name, sizeof(element_name), "[%" PRIu64 "]",
6293 static_cast<uint64_t>(idx));
6294 child_name.assign(element_name);
6295 if (Optional<uint64_t> size =
6296 element_type.GetByteSize(get_exe_scope())) {
6297 child_byte_size = *size;
6298 child_byte_offset = (int32_t)idx * (int32_t)child_byte_size;
6299 return element_type;
6300 }
6301 }
6302 }
6303 }
6304 break;
6305
6306 case clang::Type::ConstantArray:
6307 case clang::Type::IncompleteArray:
6308 if (ignore_array_bounds || idx_is_valid) {
6309 const clang::ArrayType *array = GetQualType(type)->getAsArrayTypeUnsafe();
6310 if (array) {
6311 CompilerType element_type = GetType(array->getElementType());
6312 if (element_type.GetCompleteType()) {
6313 child_name = std::string(llvm::formatv("[{0}]", idx));
6314 if (Optional<uint64_t> size =
6315 element_type.GetByteSize(get_exe_scope())) {
6316 child_byte_size = *size;
6317 child_byte_offset = (int32_t)idx * (int32_t)child_byte_size;
6318 return element_type;
6319 }
6320 }
6321 }
6322 }
6323 break;
6324
6325 case clang::Type::Pointer: {
6326 CompilerType pointee_clang_type(GetPointeeType(type));
6327
6328 // Don't dereference "void *" pointers
6329 if (pointee_clang_type.IsVoidType())
6330 return CompilerType();
6331
6332 if (transparent_pointers && pointee_clang_type.IsAggregateType()) {
6333 child_is_deref_of_parent = false;
6334 bool tmp_child_is_deref_of_parent = false;
6335 return pointee_clang_type.GetChildCompilerTypeAtIndex(
6336 exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
6337 ignore_array_bounds, child_name, child_byte_size, child_byte_offset,
6338 child_bitfield_bit_size, child_bitfield_bit_offset,
6339 child_is_base_class, tmp_child_is_deref_of_parent, valobj,
6340 language_flags);
6341 } else {
6342 child_is_deref_of_parent = true;
6343
6344 const char *parent_name =
6345 valobj ? valobj->GetName().GetCString() : nullptr;
6346 if (parent_name) {
6347 child_name.assign(1, '*');
6348 child_name += parent_name;
6349 }
6350
6351 // We have a pointer to an simple type
6352 if (idx == 0) {
6353 if (Optional<uint64_t> size =
6354 pointee_clang_type.GetByteSize(get_exe_scope())) {
6355 child_byte_size = *size;
6356 child_byte_offset = 0;
6357 return pointee_clang_type;
6358 }
6359 }
6360 }
6361 break;
6362 }
6363
6364 case clang::Type::LValueReference:
6365 case clang::Type::RValueReference:
6366 if (idx_is_valid) {
6367 const clang::ReferenceType *reference_type =
6368 llvm::cast<clang::ReferenceType>(parent_qual_type.getTypePtr());
6369 CompilerType pointee_clang_type =
6370 GetType(reference_type->getPointeeType());
6371 if (transparent_pointers && pointee_clang_type.IsAggregateType()) {
6372 child_is_deref_of_parent = false;
6373 bool tmp_child_is_deref_of_parent = false;
6374 return pointee_clang_type.GetChildCompilerTypeAtIndex(
6375 exe_ctx, idx, transparent_pointers, omit_empty_base_classes,
6376 ignore_array_bounds, child_name, child_byte_size, child_byte_offset,
6377 child_bitfield_bit_size, child_bitfield_bit_offset,
6378 child_is_base_class, tmp_child_is_deref_of_parent, valobj,
6379 language_flags);
6380 } else {
6381 const char *parent_name =
6382 valobj ? valobj->GetName().GetCString() : nullptr;
6383 if (parent_name) {
6384 child_name.assign(1, '&');
6385 child_name += parent_name;
6386 }
6387
6388 // We have a pointer to an simple type
6389 if (idx == 0) {
6390 if (Optional<uint64_t> size =
6391 pointee_clang_type.GetByteSize(get_exe_scope())) {
6392 child_byte_size = *size;
6393 child_byte_offset = 0;
6394 return pointee_clang_type;
6395 }
6396 }
6397 }
6398 }
6399 break;
6400
6401 default:
6402 break;
6403 }
6404 return CompilerType();
6405}
6406
6407static uint32_t GetIndexForRecordBase(const clang::RecordDecl *record_decl,
6408 const clang::CXXBaseSpecifier *base_spec,
6409 bool omit_empty_base_classes) {
6410 uint32_t child_idx = 0;
6411
6412 const clang::CXXRecordDecl *cxx_record_decl =
6413 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
6414
6415 if (cxx_record_decl) {
6416 clang::CXXRecordDecl::base_class_const_iterator base_class, base_class_end;
6417 for (base_class = cxx_record_decl->bases_begin(),
6418 base_class_end = cxx_record_decl->bases_end();
6419 base_class != base_class_end; ++base_class) {
6420 if (omit_empty_base_classes) {
6421 if (BaseSpecifierIsEmpty(base_class))
6422 continue;
6423 }
6424
6425 if (base_class == base_spec)
6426 return child_idx;
6427 ++child_idx;
6428 }
6429 }
6430
6431 return UINT32_MAX;
6432}
6433
6434static uint32_t GetIndexForRecordChild(const clang::RecordDecl *record_decl,
6435 clang::NamedDecl *canonical_decl,
6436 bool omit_empty_base_classes) {
6437 uint32_t child_idx = TypeSystemClang::GetNumBaseClasses(
6438 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl),
6439 omit_empty_base_classes);
6440
6441 clang::RecordDecl::field_iterator field, field_end;
6442 for (field = record_decl->field_begin(), field_end = record_decl->field_end();
6443 field != field_end; ++field, ++child_idx) {
6444 if (field->getCanonicalDecl() == canonical_decl)
6445 return child_idx;
6446 }
6447
6448 return UINT32_MAX;
6449}
6450
6451// Look for a child member (doesn't include base classes, but it does include
6452// their members) in the type hierarchy. Returns an index path into
6453// "clang_type" on how to reach the appropriate member.
6454//
6455// class A
6456// {
6457// public:
6458// int m_a;
6459// int m_b;
6460// };
6461//
6462// class B
6463// {
6464// };
6465//
6466// class C :
6467// public B,
6468// public A
6469// {
6470// };
6471//
6472// If we have a clang type that describes "class C", and we wanted to looked
6473// "m_b" in it:
6474//
6475// With omit_empty_base_classes == false we would get an integer array back
6476// with: { 1, 1 } The first index 1 is the child index for "class A" within
6477// class C The second index 1 is the child index for "m_b" within class A
6478//
6479// With omit_empty_base_classes == true we would get an integer array back
6480// with: { 0, 1 } The first index 0 is the child index for "class A" within
6481// class C (since class B doesn't have any members it doesn't count) The second
6482// index 1 is the child index for "m_b" within class A
6483
6484size_t TypeSystemClang::GetIndexOfChildMemberWithName(
6485 lldb::opaque_compiler_type_t type, const char *name,
6486 bool omit_empty_base_classes, std::vector<uint32_t> &child_indexes) {
6487 if (type && name && name[0]) {
6488 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
6489 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6490 switch (type_class) {
6491 case clang::Type::Record:
6492 if (GetCompleteType(type)) {
6493 const clang::RecordType *record_type =
6494 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
6495 const clang::RecordDecl *record_decl = record_type->getDecl();
6496
6497 assert(record_decl);
6498 uint32_t child_idx = 0;
6499
6500 const clang::CXXRecordDecl *cxx_record_decl =
6501 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
6502
6503 // Try and find a field that matches NAME
6504 clang::RecordDecl::field_iterator field, field_end;
6505 llvm::StringRef name_sref(name);
6506 for (field = record_decl->field_begin(),
6507 field_end = record_decl->field_end();
6508 field != field_end; ++field, ++child_idx) {
6509 llvm::StringRef field_name = field->getName();
6510 if (field_name.empty()) {
6511 CompilerType field_type = GetType(field->getType());
6512 child_indexes.push_back(child_idx);
6513 if (field_type.GetIndexOfChildMemberWithName(
6514 name, omit_empty_base_classes, child_indexes))
6515 return child_indexes.size();
6516 child_indexes.pop_back();
6517
6518 } else if (field_name.equals(name_sref)) {
6519 // We have to add on the number of base classes to this index!
6520 child_indexes.push_back(
6521 child_idx + TypeSystemClang::GetNumBaseClasses(
6522 cxx_record_decl, omit_empty_base_classes));
6523 return child_indexes.size();
6524 }
6525 }
6526
6527 if (cxx_record_decl) {
6528 const clang::RecordDecl *parent_record_decl = cxx_record_decl;
6529
6530 // Didn't find things easily, lets let clang do its thang...
6531 clang::IdentifierInfo &ident_ref =
6532 getASTContext().Idents.get(name_sref);
6533 clang::DeclarationName decl_name(&ident_ref);
6534
6535 clang::CXXBasePaths paths;
6536 if (cxx_record_decl->lookupInBases(
6537 [decl_name](const clang::CXXBaseSpecifier *specifier,
6538 clang::CXXBasePath &path) {
6539 path.Decls =
6540 specifier->getType()->getAsCXXRecordDecl()->lookup(
6541 decl_name);
6542 return !path.Decls.empty();
6543 },
6544 paths)) {
6545 clang::CXXBasePaths::const_paths_iterator path,
6546 path_end = paths.end();
6547 for (path = paths.begin(); path != path_end; ++path) {
6548 const size_t num_path_elements = path->size();
6549 for (size_t e = 0; e < num_path_elements; ++e) {
6550 clang::CXXBasePathElement elem = (*path)[e];
6551
6552 child_idx = GetIndexForRecordBase(parent_record_decl, elem.Base,
6553 omit_empty_base_classes);
6554 if (child_idx == UINT32_MAX) {
6555 child_indexes.clear();
6556 return 0;
6557 } else {
6558 child_indexes.push_back(child_idx);
6559 parent_record_decl = llvm::cast<clang::RecordDecl>(
6560 elem.Base->getType()
6561 ->getAs<clang::RecordType>()
6562 ->getDecl());
6563 }
6564 }
6565 for (clang::NamedDecl *path_decl : path->Decls) {
6566 child_idx = GetIndexForRecordChild(
6567 parent_record_decl, path_decl, omit_empty_base_classes);
6568 if (child_idx == UINT32_MAX) {
6569 child_indexes.clear();
6570 return 0;
6571 } else {
6572 child_indexes.push_back(child_idx);
6573 }
6574 }
6575 }
6576 return child_indexes.size();
6577 }
6578 }
6579 }
6580 break;
6581
6582 case clang::Type::ObjCObject:
6583 case clang::Type::ObjCInterface:
6584 if (GetCompleteType(type)) {
6585 llvm::StringRef name_sref(name);
6586 const clang::ObjCObjectType *objc_class_type =
6587 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
6588 assert(objc_class_type);
6589 if (objc_class_type) {
6590 uint32_t child_idx = 0;
6591 clang::ObjCInterfaceDecl *class_interface_decl =
6592 objc_class_type->getInterface();
6593
6594 if (class_interface_decl) {
6595 clang::ObjCInterfaceDecl::ivar_iterator ivar_pos,
6596 ivar_end = class_interface_decl->ivar_end();
6597 clang::ObjCInterfaceDecl *superclass_interface_decl =
6598 class_interface_decl->getSuperClass();
6599
6600 for (ivar_pos = class_interface_decl->ivar_begin();
6601 ivar_pos != ivar_end; ++ivar_pos, ++child_idx) {
6602 const clang::ObjCIvarDecl *ivar_decl = *ivar_pos;
6603
6604 if (ivar_decl->getName().equals(name_sref)) {
6605 if ((!omit_empty_base_classes && superclass_interface_decl) ||
6606 (omit_empty_base_classes &&
6607 ObjCDeclHasIVars(superclass_interface_decl, true)))
6608 ++child_idx;
6609
6610 child_indexes.push_back(child_idx);
6611 return child_indexes.size();
6612 }
6613 }
6614
6615 if (superclass_interface_decl) {
6616 // The super class index is always zero for ObjC classes, so we
6617 // push it onto the child indexes in case we find an ivar in our
6618 // superclass...
6619 child_indexes.push_back(0);
6620
6621 CompilerType superclass_clang_type =
6622 GetType(getASTContext().getObjCInterfaceType(
6623 superclass_interface_decl));
6624 if (superclass_clang_type.GetIndexOfChildMemberWithName(
6625 name, omit_empty_base_classes, child_indexes)) {
6626 // We did find an ivar in a superclass so just return the
6627 // results!
6628 return child_indexes.size();
6629 }
6630
6631 // We didn't find an ivar matching "name" in our superclass, pop
6632 // the superclass zero index that we pushed on above.
6633 child_indexes.pop_back();
6634 }
6635 }
6636 }
6637 }
6638 break;
6639
6640 case clang::Type::ObjCObjectPointer: {
6641 CompilerType objc_object_clang_type = GetType(
6642 llvm::cast<clang::ObjCObjectPointerType>(qual_type.getTypePtr())
6643 ->getPointeeType());
6644 return objc_object_clang_type.GetIndexOfChildMemberWithName(
6645 name, omit_empty_base_classes, child_indexes);
6646 } break;
6647
6648 case clang::Type::ConstantArray: {
6649 // const clang::ConstantArrayType *array =
6650 // llvm::cast<clang::ConstantArrayType>(parent_qual_type.getTypePtr());
6651 // const uint64_t element_count =
6652 // array->getSize().getLimitedValue();
6653 //
6654 // if (idx < element_count)
6655 // {
6656 // std::pair<uint64_t, unsigned> field_type_info =
6657 // ast->getTypeInfo(array->getElementType());
6658 //
6659 // char element_name[32];
6660 // ::snprintf (element_name, sizeof (element_name),
6661 // "%s[%u]", parent_name ? parent_name : "", idx);
6662 //
6663 // child_name.assign(element_name);
6664 // assert(field_type_info.first % 8 == 0);
6665 // child_byte_size = field_type_info.first / 8;
6666 // child_byte_offset = idx * child_byte_size;
6667 // return array->getElementType().getAsOpaquePtr();
6668 // }
6669 } break;
6670
6671 // case clang::Type::MemberPointerType:
6672 // {
6673 // MemberPointerType *mem_ptr_type =
6674 // llvm::cast<MemberPointerType>(qual_type.getTypePtr());
6675 // clang::QualType pointee_type =
6676 // mem_ptr_type->getPointeeType();
6677 //
6678 // if (TypeSystemClang::IsAggregateType
6679 // (pointee_type.getAsOpaquePtr()))
6680 // {
6681 // return GetIndexOfChildWithName (ast,
6682 // mem_ptr_type->getPointeeType().getAsOpaquePtr(),
6683 // name);
6684 // }
6685 // }
6686 // break;
6687 //
6688 case clang::Type::LValueReference:
6689 case clang::Type::RValueReference: {
6690 const clang::ReferenceType *reference_type =
6691 llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
6692 clang::QualType pointee_type(reference_type->getPointeeType());
6693 CompilerType pointee_clang_type = GetType(pointee_type);
6694
6695 if (pointee_clang_type.IsAggregateType()) {
6696 return pointee_clang_type.GetIndexOfChildMemberWithName(
6697 name, omit_empty_base_classes, child_indexes);
6698 }
6699 } break;
6700
6701 case clang::Type::Pointer: {
6702 CompilerType pointee_clang_type(GetPointeeType(type));
6703
6704 if (pointee_clang_type.IsAggregateType()) {
6705 return pointee_clang_type.GetIndexOfChildMemberWithName(
6706 name, omit_empty_base_classes, child_indexes);
6707 }
6708 } break;
6709
6710 default:
6711 break;
6712 }
6713 }
6714 return 0;
6715}
6716
6717// Get the index of the child of "clang_type" whose name matches. This function
6718// doesn't descend into the children, but only looks one level deep and name
6719// matches can include base class names.
6720
6721uint32_t
6722TypeSystemClang::GetIndexOfChildWithName(lldb::opaque_compiler_type_t type,
6723 const char *name,
6724 bool omit_empty_base_classes) {
6725 if (type && name && name[0]) {
6726 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
6727
6728 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6729
6730 switch (type_class) {
6731 case clang::Type::Record:
6732 if (GetCompleteType(type)) {
6733 const clang::RecordType *record_type =
6734 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
6735 const clang::RecordDecl *record_decl = record_type->getDecl();
6736
6737 assert(record_decl);
6738 uint32_t child_idx = 0;
6739
6740 const clang::CXXRecordDecl *cxx_record_decl =
6741 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
6742
6743 if (cxx_record_decl) {
6744 clang::CXXRecordDecl::base_class_const_iterator base_class,
6745 base_class_end;
6746 for (base_class = cxx_record_decl->bases_begin(),
6747 base_class_end = cxx_record_decl->bases_end();
6748 base_class != base_class_end; ++base_class) {
6749 // Skip empty base classes
6750 clang::CXXRecordDecl *base_class_decl =
6751 llvm::cast<clang::CXXRecordDecl>(
6752 base_class->getType()
6753 ->getAs<clang::RecordType>()
6754 ->getDecl());
6755 if (omit_empty_base_classes &&
6756 !TypeSystemClang::RecordHasFields(base_class_decl))
6757 continue;
6758
6759 CompilerType base_class_clang_type = GetType(base_class->getType());
6760 std::string base_class_type_name(
6761 base_class_clang_type.GetTypeName().AsCString(""));
6762 if (base_class_type_name == name)
6763 return child_idx;
6764 ++child_idx;
6765 }
6766 }
6767
6768 // Try and find a field that matches NAME
6769 clang::RecordDecl::field_iterator field, field_end;
6770 llvm::StringRef name_sref(name);
6771 for (field = record_decl->field_begin(),
6772 field_end = record_decl->field_end();
6773 field != field_end; ++field, ++child_idx) {
6774 if (field->getName().equals(name_sref))
6775 return child_idx;
6776 }
6777 }
6778 break;
6779
6780 case clang::Type::ObjCObject:
6781 case clang::Type::ObjCInterface:
6782 if (GetCompleteType(type)) {
6783 llvm::StringRef name_sref(name);
6784 const clang::ObjCObjectType *objc_class_type =
6785 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
6786 assert(objc_class_type);
6787 if (objc_class_type) {
6788 uint32_t child_idx = 0;
6789 clang::ObjCInterfaceDecl *class_interface_decl =
6790 objc_class_type->getInterface();
6791
6792 if (class_interface_decl) {
6793 clang::ObjCInterfaceDecl::ivar_iterator ivar_pos,
6794 ivar_end = class_interface_decl->ivar_end();
6795 clang::ObjCInterfaceDecl *superclass_interface_decl =
6796 class_interface_decl->getSuperClass();
6797
6798 for (ivar_pos = class_interface_decl->ivar_begin();
6799 ivar_pos != ivar_end; ++ivar_pos, ++child_idx) {
6800 const clang::ObjCIvarDecl *ivar_decl = *ivar_pos;
6801
6802 if (ivar_decl->getName().equals(name_sref)) {
6803 if ((!omit_empty_base_classes && superclass_interface_decl) ||
6804 (omit_empty_base_classes &&
6805 ObjCDeclHasIVars(superclass_interface_decl, true)))
6806 ++child_idx;
6807
6808 return child_idx;
6809 }
6810 }
6811
6812 if (superclass_interface_decl) {
6813 if (superclass_interface_decl->getName().equals(name_sref))
6814 return 0;
6815 }
6816 }
6817 }
6818 }
6819 break;
6820
6821 case clang::Type::ObjCObjectPointer: {
6822 CompilerType pointee_clang_type = GetType(
6823 llvm::cast<clang::ObjCObjectPointerType>(qual_type.getTypePtr())
6824 ->getPointeeType());
6825 return pointee_clang_type.GetIndexOfChildWithName(
6826 name, omit_empty_base_classes);
6827 } break;
6828
6829 case clang::Type::ConstantArray: {
6830 // const clang::ConstantArrayType *array =
6831 // llvm::cast<clang::ConstantArrayType>(parent_qual_type.getTypePtr());
6832 // const uint64_t element_count =
6833 // array->getSize().getLimitedValue();
6834 //
6835 // if (idx < element_count)
6836 // {
6837 // std::pair<uint64_t, unsigned> field_type_info =
6838 // ast->getTypeInfo(array->getElementType());
6839 //
6840 // char element_name[32];
6841 // ::snprintf (element_name, sizeof (element_name),
6842 // "%s[%u]", parent_name ? parent_name : "", idx);
6843 //
6844 // child_name.assign(element_name);
6845 // assert(field_type_info.first % 8 == 0);
6846 // child_byte_size = field_type_info.first / 8;
6847 // child_byte_offset = idx * child_byte_size;
6848 // return array->getElementType().getAsOpaquePtr();
6849 // }
6850 } break;
6851
6852 // case clang::Type::MemberPointerType:
6853 // {
6854 // MemberPointerType *mem_ptr_type =
6855 // llvm::cast<MemberPointerType>(qual_type.getTypePtr());
6856 // clang::QualType pointee_type =
6857 // mem_ptr_type->getPointeeType();
6858 //
6859 // if (TypeSystemClang::IsAggregateType
6860 // (pointee_type.getAsOpaquePtr()))
6861 // {
6862 // return GetIndexOfChildWithName (ast,
6863 // mem_ptr_type->getPointeeType().getAsOpaquePtr(),
6864 // name);
6865 // }
6866 // }
6867 // break;
6868 //
6869 case clang::Type::LValueReference:
6870 case clang::Type::RValueReference: {
6871 const clang::ReferenceType *reference_type =
6872 llvm::cast<clang::ReferenceType>(qual_type.getTypePtr());
6873 CompilerType pointee_type = GetType(reference_type->getPointeeType());
6874
6875 if (pointee_type.IsAggregateType()) {
6876 return pointee_type.GetIndexOfChildWithName(name,
6877 omit_empty_base_classes);
6878 }
6879 } break;
6880
6881 case clang::Type::Pointer: {
6882 const clang::PointerType *pointer_type =
6883 llvm::cast<clang::PointerType>(qual_type.getTypePtr());
6884 CompilerType pointee_type = GetType(pointer_type->getPointeeType());
6885
6886 if (pointee_type.IsAggregateType()) {
6887 return pointee_type.GetIndexOfChildWithName(name,
6888 omit_empty_base_classes);
6889 } else {
6890 // if (parent_name)
6891 // {
6892 // child_name.assign(1, '*');
6893 // child_name += parent_name;
6894 // }
6895 //
6896 // // We have a pointer to an simple type
6897 // if (idx == 0)
6898 // {
6899 // std::pair<uint64_t, unsigned> clang_type_info
6900 // = ast->getTypeInfo(pointee_type);
6901 // assert(clang_type_info.first % 8 == 0);
6902 // child_byte_size = clang_type_info.first / 8;
6903 // child_byte_offset = 0;
6904 // return pointee_type.getAsOpaquePtr();
6905 // }
6906 }
6907 } break;
6908
6909 default:
6910 break;
6911 }
6912 }
6913 return UINT32_MAX;
6914}
6915
6916size_t
6917TypeSystemClang::GetNumTemplateArguments(lldb::opaque_compiler_type_t type) {
6918 if (!type)
6919 return 0;
6920
6921 clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type));
6922 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6923 switch (type_class) {
6924 case clang::Type::Record:
6925 if (GetCompleteType(type)) {
6926 const clang::CXXRecordDecl *cxx_record_decl =
6927 qual_type->getAsCXXRecordDecl();
6928 if (cxx_record_decl) {
6929 const clang::ClassTemplateSpecializationDecl *template_decl =
6930 llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(
6931 cxx_record_decl);
6932 if (template_decl)
6933 return template_decl->getTemplateArgs().size();
6934 }
6935 }
6936 break;
6937
6938 default:
6939 break;
6940 }
6941
6942 return 0;
6943}
6944
6945const clang::ClassTemplateSpecializationDecl *
6946TypeSystemClang::GetAsTemplateSpecialization(
6947 lldb::opaque_compiler_type_t type) {
6948 if (!type)
6949 return nullptr;
6950
6951 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
6952 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
6953 switch (type_class) {
6954 case clang::Type::Record: {
6955 if (! GetCompleteType(type))
6956 return nullptr;
6957 const clang::CXXRecordDecl *cxx_record_decl =
6958 qual_type->getAsCXXRecordDecl();
6959 if (!cxx_record_decl)
6960 return nullptr;
6961 return llvm::dyn_cast<clang::ClassTemplateSpecializationDecl>(
6962 cxx_record_decl);
6963 }
6964
6965 default:
6966 return nullptr;
6967 }
6968}
6969
6970lldb::TemplateArgumentKind
6971TypeSystemClang::GetTemplateArgumentKind(lldb::opaque_compiler_type_t type,
6972 size_t arg_idx) {
6973 const clang::ClassTemplateSpecializationDecl *template_decl =
6974 GetAsTemplateSpecialization(type);
6975 if (! template_decl || arg_idx >= template_decl->getTemplateArgs().size())
6976 return eTemplateArgumentKindNull;
6977
6978 switch (template_decl->getTemplateArgs()[arg_idx].getKind()) {
6979 case clang::TemplateArgument::Null:
6980 return eTemplateArgumentKindNull;
6981
6982 case clang::TemplateArgument::NullPtr:
6983 return eTemplateArgumentKindNullPtr;
6984
6985 case clang::TemplateArgument::Type:
6986 return eTemplateArgumentKindType;
6987
6988 case clang::TemplateArgument::Declaration:
6989 return eTemplateArgumentKindDeclaration;
6990
6991 case clang::TemplateArgument::Integral:
6992 return eTemplateArgumentKindIntegral;
6993
6994 case clang::TemplateArgument::Template:
6995 return eTemplateArgumentKindTemplate;
6996
6997 case clang::TemplateArgument::TemplateExpansion:
6998 return eTemplateArgumentKindTemplateExpansion;
6999
7000 case clang::TemplateArgument::Expression:
7001 return eTemplateArgumentKindExpression;
7002
7003 case clang::TemplateArgument::Pack:
7004 return eTemplateArgumentKindPack;
7005 }
7006 llvm_unreachable("Unhandled clang::TemplateArgument::ArgKind");
7007}
7008
7009CompilerType
7010TypeSystemClang::GetTypeTemplateArgument(lldb::opaque_compiler_type_t type,
7011 size_t idx) {
7012 const clang::ClassTemplateSpecializationDecl *template_decl =
7013 GetAsTemplateSpecialization(type);
7014 if (!template_decl || idx >= template_decl->getTemplateArgs().size())
7015 return CompilerType();
7016
7017 const clang::TemplateArgument &template_arg =
7018 template_decl->getTemplateArgs()[idx];
7019 if (template_arg.getKind() != clang::TemplateArgument::Type)
7020 return CompilerType();
7021
7022 return GetType(template_arg.getAsType());
7023}
7024
7025Optional<CompilerType::IntegralTemplateArgument>
7026TypeSystemClang::GetIntegralTemplateArgument(lldb::opaque_compiler_type_t type,
7027 size_t idx) {
7028 const clang::ClassTemplateSpecializationDecl *template_decl =
7029 GetAsTemplateSpecialization(type);
7030 if (! template_decl || idx >= template_decl->getTemplateArgs().size())
7031 return llvm::None;
7032
7033 const clang::TemplateArgument &template_arg =
7034 template_decl->getTemplateArgs()[idx];
7035 if (template_arg.getKind() != clang::TemplateArgument::Integral)
7036 return llvm::None;
7037
7038 return {
7039 {template_arg.getAsIntegral(), GetType(template_arg.getIntegralType())}};
7040}
7041
7042CompilerType TypeSystemClang::GetTypeForFormatters(void *type) {
7043 if (type)
7044 return ClangUtil::RemoveFastQualifiers(CompilerType(this, type));
7045 return CompilerType();
7046}
7047
7048clang::EnumDecl *TypeSystemClang::GetAsEnumDecl(const CompilerType &type) {
7049 const clang::EnumType *enutype =
7050 llvm::dyn_cast<clang::EnumType>(ClangUtil::GetCanonicalQualType(type));
7051 if (enutype)
7052 return enutype->getDecl();
7053 return nullptr;
7054}
7055
7056clang::RecordDecl *TypeSystemClang::GetAsRecordDecl(const CompilerType &type) {
7057 const clang::RecordType *record_type =
7058 llvm::dyn_cast<clang::RecordType>(ClangUtil::GetCanonicalQualType(type));
7059 if (record_type)
7060 return record_type->getDecl();
7061 return nullptr;
7062}
7063
7064clang::TagDecl *TypeSystemClang::GetAsTagDecl(const CompilerType &type) {
7065 return ClangUtil::GetAsTagDecl(type);
7066}
7067
7068clang::TypedefNameDecl *
7069TypeSystemClang::GetAsTypedefDecl(const CompilerType &type) {
7070 const clang::TypedefType *typedef_type =
7071 llvm::dyn_cast<clang::TypedefType>(ClangUtil::GetQualType(type));
7072 if (typedef_type)
7073 return typedef_type->getDecl();
7074 return nullptr;
7075}
7076
7077clang::CXXRecordDecl *
7078TypeSystemClang::GetAsCXXRecordDecl(lldb::opaque_compiler_type_t type) {
7079 return GetCanonicalQualType(type)->getAsCXXRecordDecl();
7080}
7081
7082clang::ObjCInterfaceDecl *
7083TypeSystemClang::GetAsObjCInterfaceDecl(const CompilerType &type) {
7084 const clang::ObjCObjectType *objc_class_type =
7085 llvm::dyn_cast<clang::ObjCObjectType>(
7086 ClangUtil::GetCanonicalQualType(type));
7087 if (objc_class_type)
7088 return objc_class_type->getInterface();
7089 return nullptr;
7090}
7091
7092clang::FieldDecl *TypeSystemClang::AddFieldToRecordType(
7093 const CompilerType &type, llvm::StringRef name,
7094 const CompilerType &field_clang_type, AccessType access,
7095 uint32_t bitfield_bit_size) {
7096 if (!type.IsValid() || !field_clang_type.IsValid())
7097 return nullptr;
7098 TypeSystemClang *ast =
7099 llvm::dyn_cast_or_null<TypeSystemClang>(type.GetTypeSystem());
7100 if (!ast)
7101 return nullptr;
7102 clang::ASTContext &clang_ast = ast->getASTContext();
7103 clang::IdentifierInfo *ident = nullptr;
7104 if (!name.empty())
7105 ident = &clang_ast.Idents.get(name);
7106
7107 clang::FieldDecl *field = nullptr;
7108
7109 clang::Expr *bit_width = nullptr;
7110 if (bitfield_bit_size != 0) {
7111 llvm::APInt bitfield_bit_size_apint(clang_ast.getTypeSize(clang_ast.IntTy),
7112 bitfield_bit_size);
7113 bit_width = new (clang_ast)
7114 clang::IntegerLiteral(clang_ast, bitfield_bit_size_apint,
7115 clang_ast.IntTy, clang::SourceLocation());
7116 }
7117
7118 clang::RecordDecl *record_decl = ast->GetAsRecordDecl(type);
7119 if (record_decl) {
7120 field = clang::FieldDecl::CreateDeserialized(clang_ast, 0);
7121 field->setDeclContext(record_decl);
7122 field->setDeclName(ident);
7123 field->setType(ClangUtil::GetQualType(field_clang_type));
7124 if (bit_width)
7125 field->setBitWidth(bit_width);
7126 SetMemberOwningModule(field, record_decl);
7127
7128 if (name.empty()) {
7129 // Determine whether this field corresponds to an anonymous struct or
7130 // union.
7131 if (const clang::TagType *TagT =
7132 field->getType()->getAs<clang::TagType>()) {
7133 if (clang::RecordDecl *Rec =
7134 llvm::dyn_cast<clang::RecordDecl>(TagT->getDecl()))
7135 if (!Rec->getDeclName()) {
7136 Rec->setAnonymousStructOrUnion(true);
7137 field->setImplicit();
7138 }
7139 }
7140 }
7141
7142 if (field) {
7143 field->setAccess(
7144 TypeSystemClang::ConvertAccessTypeToAccessSpecifier(access));
7145
7146 record_decl->addDecl(field);
7147
7148 VerifyDecl(field);
7149 }
7150 } else {
7151 clang::ObjCInterfaceDecl *class_interface_decl =
7152 ast->GetAsObjCInterfaceDecl(type);
7153
7154 if (class_interface_decl) {
7155 const bool is_synthesized = false;
7156
7157 field_clang_type.GetCompleteType();
7158
7159 auto *ivar = clang::ObjCIvarDecl::CreateDeserialized(clang_ast, 0);
7160 ivar->setDeclContext(class_interface_decl);
7161 ivar->setDeclName(ident);
7162 ivar->setType(ClangUtil::GetQualType(field_clang_type));
7163 ivar->setAccessControl(ConvertAccessTypeToObjCIvarAccessControl(access));
7164 if (bit_width)
7165 ivar->setBitWidth(bit_width);
7166 ivar->setSynthesize(is_synthesized);
7167 field = ivar;
7168 SetMemberOwningModule(field, class_interface_decl);
7169
7170 if (field) {
7171 class_interface_decl->addDecl(field);
7172
7173 VerifyDecl(field);
7174 }
7175 }
7176 }
7177 return field;
7178}
7179
7180void TypeSystemClang::BuildIndirectFields(const CompilerType &type) {
7181 if (!type)
7182 return;
7183
7184 TypeSystemClang *ast = llvm::dyn_cast<TypeSystemClang>(type.GetTypeSystem());
7185 if (!ast)
7186 return;
7187
7188 clang::RecordDecl *record_decl = ast->GetAsRecordDecl(type);
7189
7190 if (!record_decl)
7191 return;
7192
7193 typedef llvm::SmallVector<clang::IndirectFieldDecl *, 1> IndirectFieldVector;
7194
7195 IndirectFieldVector indirect_fields;
7196 clang::RecordDecl::field_iterator field_pos;
7197 clang::RecordDecl::field_iterator field_end_pos = record_decl->field_end();
7198 clang::RecordDecl::field_iterator last_field_pos = field_end_pos;
7199 for (field_pos = record_decl->field_begin(); field_pos != field_end_pos;
7200 last_field_pos = field_pos++) {
7201 if (field_pos->isAnonymousStructOrUnion()) {
7202 clang::QualType field_qual_type = field_pos->getType();
7203
7204 const clang::RecordType *field_record_type =
7205 field_qual_type->getAs<clang::RecordType>();
7206
7207 if (!field_record_type)
7208 continue;
7209
7210 clang::RecordDecl *field_record_decl = field_record_type->getDecl();
7211
7212 if (!field_record_decl)
7213 continue;
7214
7215 for (clang::RecordDecl::decl_iterator
7216 di = field_record_decl->decls_begin(),
7217 de = field_record_decl->decls_end();
7218 di != de; ++di) {
7219 if (clang::FieldDecl *nested_field_decl =
7220 llvm::dyn_cast<clang::FieldDecl>(*di)) {
7221 clang::NamedDecl **chain =
7222 new (ast->getASTContext()) clang::NamedDecl *[2];
7223 chain[0] = *field_pos;
7224 chain[1] = nested_field_decl;
7225 clang::IndirectFieldDecl *indirect_field =
7226 clang::IndirectFieldDecl::Create(
7227 ast->getASTContext(), record_decl, clang::SourceLocation(),
7228 nested_field_decl->getIdentifier(),
7229 nested_field_decl->getType(), {chain, 2});
7230 SetMemberOwningModule(indirect_field, record_decl);
7231
7232 indirect_field->setImplicit();
7233
7234 indirect_field->setAccess(TypeSystemClang::UnifyAccessSpecifiers(
7235 field_pos->getAccess(), nested_field_decl->getAccess()));
7236
7237 indirect_fields.push_back(indirect_field);
7238 } else if (clang::IndirectFieldDecl *nested_indirect_field_decl =
7239 llvm::dyn_cast<clang::IndirectFieldDecl>(*di)) {
7240 size_t nested_chain_size =
7241 nested_indirect_field_decl->getChainingSize();
7242 clang::NamedDecl **chain = new (ast->getASTContext())
7243 clang::NamedDecl *[nested_chain_size + 1];
7244 chain[0] = *field_pos;
7245
7246 int chain_index = 1;
7247 for (clang::IndirectFieldDecl::chain_iterator
7248 nci = nested_indirect_field_decl->chain_begin(),
7249 nce = nested_indirect_field_decl->chain_end();
7250 nci < nce; ++nci) {
7251 chain[chain_index] = *nci;
7252 chain_index++;
7253 }
7254
7255 clang::IndirectFieldDecl *indirect_field =
7256 clang::IndirectFieldDecl::Create(
7257 ast->getASTContext(), record_decl, clang::SourceLocation(),
7258 nested_indirect_field_decl->getIdentifier(),
7259 nested_indirect_field_decl->getType(),
7260 {chain, nested_chain_size + 1});
7261 SetMemberOwningModule(indirect_field, record_decl);
7262
7263 indirect_field->setImplicit();
7264
7265 indirect_field->setAccess(TypeSystemClang::UnifyAccessSpecifiers(
7266 field_pos->getAccess(), nested_indirect_field_decl->getAccess()));
7267
7268 indirect_fields.push_back(indirect_field);
7269 }
7270 }
7271 }
7272 }
7273
7274 // Check the last field to see if it has an incomplete array type as its last
7275 // member and if it does, the tell the record decl about it
7276 if (last_field_pos != field_end_pos) {
7277 if (last_field_pos->getType()->isIncompleteArrayType())
7278 record_decl->hasFlexibleArrayMember();
7279 }
7280
7281 for (IndirectFieldVector::iterator ifi = indirect_fields.begin(),
7282 ife = indirect_fields.end();
7283 ifi < ife; ++ifi) {
7284 record_decl->addDecl(*ifi);
7285 }
7286}
7287
7288void TypeSystemClang::SetIsPacked(const CompilerType &type) {
7289 if (type) {
7290 TypeSystemClang *ast =
7291 llvm::dyn_cast<TypeSystemClang>(type.GetTypeSystem());
7292 if (ast) {
7293 clang::RecordDecl *record_decl = GetAsRecordDecl(type);
7294
7295 if (!record_decl)
7296 return;
7297
7298 record_decl->addAttr(
7299 clang::PackedAttr::CreateImplicit(ast->getASTContext()));
7300 }
7301 }
7302}
7303
7304clang::VarDecl *TypeSystemClang::AddVariableToRecordType(
7305 const CompilerType &type, llvm::StringRef name,
7306 const CompilerType &var_type, AccessType access) {
7307 if (!type.IsValid() || !var_type.IsValid())
7308 return nullptr;
7309
7310 TypeSystemClang *ast = llvm::dyn_cast<TypeSystemClang>(type.GetTypeSystem());
7311 if (!ast)
7312 return nullptr;
7313
7314 clang::RecordDecl *record_decl = ast->GetAsRecordDecl(type);
7315 if (!record_decl)
7316 return nullptr;
7317
7318 clang::VarDecl *var_decl = nullptr;
7319 clang::IdentifierInfo *ident = nullptr;
7320 if (!name.empty())
7321 ident = &ast->getASTContext().Idents.get(name);
7322
7323 var_decl = clang::VarDecl::CreateDeserialized(ast->getASTContext(), 0);
7324 var_decl->setDeclContext(record_decl);
7325 var_decl->setDeclName(ident);
7326 var_decl->setType(ClangUtil::GetQualType(var_type));
7327 var_decl->setStorageClass(clang::SC_Static);
7328 SetMemberOwningModule(var_decl, record_decl);
7329 if (!var_decl)
7330 return nullptr;
7331
7332 var_decl->setAccess(
7333 TypeSystemClang::ConvertAccessTypeToAccessSpecifier(access));
7334 record_decl->addDecl(var_decl);
7335
7336 VerifyDecl(var_decl);
7337
7338 return var_decl;
7339}
7340
7341void TypeSystemClang::SetIntegerInitializerForVariable(
7342 VarDecl *var, const llvm::APInt &init_value) {
7343 assert(!var->hasInit() && "variable already initialized");
7344
7345 clang::ASTContext &ast = var->getASTContext();
7346 QualType qt = var->getType();
7347 assert(qt->isIntegralOrEnumerationType() &&
7348 "only integer or enum types supported");
7349 // If the variable is an enum type, take the underlying integer type as
7350 // the type of the integer literal.
7351 if (const EnumType *enum_type = llvm::dyn_cast<EnumType>(qt.getTypePtr())) {
7352 const EnumDecl *enum_decl = enum_type->getDecl();
7353 qt = enum_decl->getIntegerType();
7354 }
7355 var->setInit(IntegerLiteral::Create(ast, init_value, qt.getUnqualifiedType(),
7356 SourceLocation()));
7357}
7358
7359void TypeSystemClang::SetFloatingInitializerForVariable(
7360 clang::VarDecl *var, const llvm::APFloat &init_value) {
7361 assert(!var->hasInit() && "variable already initialized");
7362
7363 clang::ASTContext &ast = var->getASTContext();
7364 QualType qt = var->getType();
7365 assert(qt->isFloatingType() && "only floating point types supported");
7366 var->setInit(FloatingLiteral::Create(
7367 ast, init_value, true, qt.getUnqualifiedType(), SourceLocation()));
7368}
7369
7370clang::CXXMethodDecl *TypeSystemClang::AddMethodToCXXRecordType(
7371 lldb::opaque_compiler_type_t type, llvm::StringRef name,
7372 const char *mangled_name, const CompilerType &method_clang_type,
7373 lldb::AccessType access, bool is_virtual, bool is_static, bool is_inline,
7374 bool is_explicit, bool is_attr_used, bool is_artificial) {
7375 if (!type || !method_clang_type.IsValid() || name.empty())
7376 return nullptr;
7377
7378 clang::QualType record_qual_type(GetCanonicalQualType(type));
7379
7380 clang::CXXRecordDecl *cxx_record_decl =
7381 record_qual_type->getAsCXXRecordDecl();
7382
7383 if (cxx_record_decl == nullptr)
7384 return nullptr;
7385
7386 clang::QualType method_qual_type(ClangUtil::GetQualType(method_clang_type));
7387
7388 clang::CXXMethodDecl *cxx_method_decl = nullptr;
7389
7390 clang::DeclarationName decl_name(&getASTContext().Idents.get(name));
7391
7392 const clang::FunctionType *function_type =
7393 llvm::dyn_cast<clang::FunctionType>(method_qual_type.getTypePtr());
7394
7395 if (function_type == nullptr)
7396 return nullptr;
7397
7398 const clang::FunctionProtoType *method_function_prototype(
7399 llvm::dyn_cast<clang::FunctionProtoType>(function_type));
7400
7401 if (!method_function_prototype)
7402 return nullptr;
7403
7404 unsigned int num_params = method_function_prototype->getNumParams();
7405
7406 clang::CXXDestructorDecl *cxx_dtor_decl(nullptr);
7407 clang::CXXConstructorDecl *cxx_ctor_decl(nullptr);
7408
7409 if (is_artificial)
7410 return nullptr; // skip everything artificial
7411
7412 const clang::ExplicitSpecifier explicit_spec(
7413 nullptr /*expr*/, is_explicit ? clang::ExplicitSpecKind::ResolvedTrue
7414 : clang::ExplicitSpecKind::ResolvedFalse);
7415
7416 if (name.startswith("~")) {
7417 cxx_dtor_decl =
7418 clang::CXXDestructorDecl::CreateDeserialized(getASTContext(), 0);
7419 cxx_dtor_decl->setDeclContext(cxx_record_decl);
7420 cxx_dtor_decl->setDeclName(
7421 getASTContext().DeclarationNames.getCXXDestructorName(
7422 getASTContext().getCanonicalType(record_qual_type)));
7423 cxx_dtor_decl->setType(method_qual_type);
7424 cxx_dtor_decl->setImplicit(is_artificial);
7425 cxx_dtor_decl->setInlineSpecified(is_inline);
7426 cxx_dtor_decl->setConstexprKind(ConstexprSpecKind::Unspecified);
7427 cxx_method_decl = cxx_dtor_decl;
7428 } else if (decl_name == cxx_record_decl->getDeclName()) {
7429 cxx_ctor_decl = clang::CXXConstructorDecl::CreateDeserialized(
7430 getASTContext(), 0, 0);
7431 cxx_ctor_decl->setDeclContext(cxx_record_decl);
7432 cxx_ctor_decl->setDeclName(
7433 getASTContext().DeclarationNames.getCXXConstructorName(
7434 getASTContext().getCanonicalType(record_qual_type)));
7435 cxx_ctor_decl->setType(method_qual_type);
7436 cxx_ctor_decl->setImplicit(is_artificial);
7437 cxx_ctor_decl->setInlineSpecified(is_inline);
7438 cxx_ctor_decl->setConstexprKind(ConstexprSpecKind::Unspecified);
7439 cxx_ctor_decl->setNumCtorInitializers(0);
7440 cxx_ctor_decl->setExplicitSpecifier(explicit_spec);
7441 cxx_method_decl = cxx_ctor_decl;
7442 } else {
7443 clang::StorageClass SC = is_static ? clang::SC_Static : clang::SC_None;
7444 clang::OverloadedOperatorKind op_kind = clang::NUM_OVERLOADED_OPERATORS;
7445
7446 if (IsOperator(name, op_kind)) {
7447 if (op_kind != clang::NUM_OVERLOADED_OPERATORS) {
7448 // Check the number of operator parameters. Sometimes we have seen bad
7449 // DWARF that doesn't correctly describe operators and if we try to
7450 // create a method and add it to the class, clang will assert and
7451 // crash, so we need to make sure things are acceptable.
7452 const bool is_method = true;
7453 if (!TypeSystemClang::CheckOverloadedOperatorKindParameterCount(
7454 is_method, op_kind, num_params))
7455 return nullptr;
7456 cxx_method_decl =
7457 clang::CXXMethodDecl::CreateDeserialized(getASTContext(), 0);
7458 cxx_method_decl->setDeclContext(cxx_record_decl);
7459 cxx_method_decl->setDeclName(
7460 getASTContext().DeclarationNames.getCXXOperatorName(op_kind));
7461 cxx_method_decl->setType(method_qual_type);
7462 cxx_method_decl->setStorageClass(SC);
7463 cxx_method_decl->setInlineSpecified(is_inline);
7464 cxx_method_decl->setConstexprKind(ConstexprSpecKind::Unspecified);
7465 } else if (num_params == 0) {
7466 // Conversion operators don't take params...
7467 auto *cxx_conversion_decl =
7468 clang::CXXConversionDecl::CreateDeserialized(getASTContext(), 0);
7469 cxx_conversion_decl->setDeclContext(cxx_record_decl);
7470 cxx_conversion_decl->setDeclName(
7471 getASTContext().DeclarationNames.getCXXConversionFunctionName(
7472 getASTContext().getCanonicalType(
7473 function_type->getReturnType())));
7474 cxx_conversion_decl->setType(method_qual_type);
7475 cxx_conversion_decl->setInlineSpecified(is_inline);
7476 cxx_conversion_decl->setExplicitSpecifier(explicit_spec);
7477 cxx_conversion_decl->setConstexprKind(ConstexprSpecKind::Unspecified);
7478 cxx_method_decl = cxx_conversion_decl;
7479 }
7480 }
7481
7482 if (cxx_method_decl == nullptr) {
7483 cxx_method_decl =
7484 clang::CXXMethodDecl::CreateDeserialized(getASTContext(), 0);
7485 cxx_method_decl->setDeclContext(cxx_record_decl);
7486 cxx_method_decl->setDeclName(decl_name);
7487 cxx_method_decl->setType(method_qual_type);
7488 cxx_method_decl->setInlineSpecified(is_inline);
7489 cxx_method_decl->setStorageClass(SC);
7490 cxx_method_decl->setConstexprKind(ConstexprSpecKind::Unspecified);
7491 }
7492 }
7493 SetMemberOwningModule(cxx_method_decl, cxx_record_decl);
7494
7495 clang::AccessSpecifier access_specifier =
7496 TypeSystemClang::ConvertAccessTypeToAccessSpecifier(access);
7497
7498 cxx_method_decl->setAccess(access_specifier);
7499 cxx_method_decl->setVirtualAsWritten(is_virtual);
7500
7501 if (is_attr_used)
7502 cxx_method_decl->addAttr(clang::UsedAttr::CreateImplicit(getASTContext()));
7503
7504 if (mangled_name != nullptr) {
7505 cxx_method_decl->addAttr(clang::AsmLabelAttr::CreateImplicit(
7506 getASTContext(), mangled_name, /*literal=*/false));
7507 }
7508
7509 // Populate the method decl with parameter decls
7510
7511 llvm::SmallVector<clang::ParmVarDecl *, 12> params;
7512
7513 for (unsigned param_index = 0; param_index < num_params; ++param_index) {
7514 params.push_back(clang::ParmVarDecl::Create(
7515 getASTContext(), cxx_method_decl, clang::SourceLocation(),
7516 clang::SourceLocation(),
7517 nullptr, // anonymous
7518 method_function_prototype->getParamType(param_index), nullptr,
7519 clang::SC_None, nullptr));
7520 }
7521
7522 cxx_method_decl->setParams(llvm::ArrayRef<clang::ParmVarDecl *>(params));
7523
7524 cxx_record_decl->addDecl(cxx_method_decl);
7525
7526 // Sometimes the debug info will mention a constructor (default/copy/move),
7527 // destructor, or assignment operator (copy/move) but there won't be any
7528 // version of this in the code. So we check if the function was artificially
7529 // generated and if it is trivial and this lets the compiler/backend know
7530 // that it can inline the IR for these when it needs to and we can avoid a
7531 // "missing function" error when running expressions.
7532
7533 if (is_artificial) {
7534 if (cxx_ctor_decl && ((cxx_ctor_decl->isDefaultConstructor() &&
7535 cxx_record_decl->hasTrivialDefaultConstructor()) ||
7536 (cxx_ctor_decl->isCopyConstructor() &&
7537 cxx_record_decl->hasTrivialCopyConstructor()) ||
7538 (cxx_ctor_decl->isMoveConstructor() &&
7539 cxx_record_decl->hasTrivialMoveConstructor()))) {
7540 cxx_ctor_decl->setDefaulted();
7541 cxx_ctor_decl->setTrivial(true);
7542 } else if (cxx_dtor_decl) {
7543 if (cxx_record_decl->hasTrivialDestructor()) {
7544 cxx_dtor_decl->setDefaulted();
7545 cxx_dtor_decl->setTrivial(true);
7546 }
7547 } else if ((cxx_method_decl->isCopyAssignmentOperator() &&
7548 cxx_record_decl->hasTrivialCopyAssignment()) ||
7549 (cxx_method_decl->isMoveAssignmentOperator() &&
7550 cxx_record_decl->hasTrivialMoveAssignment())) {
7551 cxx_method_decl->setDefaulted();
7552 cxx_method_decl->setTrivial(true);
7553 }
7554 }
7555
7556 VerifyDecl(cxx_method_decl);
7557
7558 return cxx_method_decl;
7559}
7560
7561void TypeSystemClang::AddMethodOverridesForCXXRecordType(
7562 lldb::opaque_compiler_type_t type) {
7563 if (auto *record = GetAsCXXRecordDecl(type))
7564 for (auto *method : record->methods())
7565 addOverridesForMethod(method);
7566}
7567
7568#pragma mark C++ Base Classes
7569
7570std::unique_ptr<clang::CXXBaseSpecifier>
7571TypeSystemClang::CreateBaseClassSpecifier(lldb::opaque_compiler_type_t type,
7572 AccessType access, bool is_virtual,
7573 bool base_of_class) {
7574 if (!type)
7575 return nullptr;
7576
7577 return std::make_unique<clang::CXXBaseSpecifier>(
7578 clang::SourceRange(), is_virtual, base_of_class,
7579 TypeSystemClang::ConvertAccessTypeToAccessSpecifier(access),
7580 getASTContext().getTrivialTypeSourceInfo(GetQualType(type)),
7581 clang::SourceLocation());
7582}
7583
7584bool TypeSystemClang::TransferBaseClasses(
7585 lldb::opaque_compiler_type_t type,
7586 std::vector<std::unique_ptr<clang::CXXBaseSpecifier>> bases) {
7587 if (!type)
7588 return false;
7589 clang::CXXRecordDecl *cxx_record_decl = GetAsCXXRecordDecl(type);
7590 if (!cxx_record_decl)
7591 return false;
7592 std::vector<clang::CXXBaseSpecifier *> raw_bases;
7593 raw_bases.reserve(bases.size());
7594
7595 // Clang will make a copy of them, so it's ok that we pass pointers that we're
7596 // about to destroy.
7597 for (auto &b : bases)
7598 raw_bases.push_back(b.get());
7599 cxx_record_decl->setBases(raw_bases.data(), raw_bases.size());
7600 return true;
7601}
7602
7603bool TypeSystemClang::SetObjCSuperClass(
7604 const CompilerType &type, const CompilerType &superclass_clang_type) {
7605 TypeSystemClang *ast =
7606 llvm::dyn_cast_or_null<TypeSystemClang>(type.GetTypeSystem());
7607 if (!ast)
7608 return false;
7609 clang::ASTContext &clang_ast = ast->getASTContext();
7610
7611 if (type && superclass_clang_type.IsValid() &&
7612 superclass_clang_type.GetTypeSystem() == type.GetTypeSystem()) {
7613 clang::ObjCInterfaceDecl *class_interface_decl =
7614 GetAsObjCInterfaceDecl(type);
7615 clang::ObjCInterfaceDecl *super_interface_decl =
7616 GetAsObjCInterfaceDecl(superclass_clang_type);
7617 if (class_interface_decl && super_interface_decl) {
7618 class_interface_decl->setSuperClass(clang_ast.getTrivialTypeSourceInfo(
7619 clang_ast.getObjCInterfaceType(super_interface_decl)));
7620 return true;
7621 }
7622 }
7623 return false;
7624}
7625
7626bool TypeSystemClang::AddObjCClassProperty(
7627 const CompilerType &type, const char *property_name,
7628 const CompilerType &property_clang_type, clang::ObjCIvarDecl *ivar_decl,
7629 const char *property_setter_name, const char *property_getter_name,
7630 uint32_t property_attributes, ClangASTMetadata *metadata) {
7631 if (!type || !property_clang_type.IsValid() || property_name == nullptr ||
7632 property_name[0] == '\0')
7633 return false;
7634 TypeSystemClang *ast = llvm::dyn_cast<TypeSystemClang>(type.GetTypeSystem());
7635 if (!ast)
7636 return false;
7637 clang::ASTContext &clang_ast = ast->getASTContext();
7638
7639 clang::ObjCInterfaceDecl *class_interface_decl = GetAsObjCInterfaceDecl(type);
7640 if (!class_interface_decl)
7641 return false;
7642
7643 CompilerType property_clang_type_to_access;
7644
7645 if (property_clang_type.IsValid())
7646 property_clang_type_to_access = property_clang_type;
7647 else if (ivar_decl)
7648 property_clang_type_to_access = ast->GetType(ivar_decl->getType());
7649
7650 if (!class_interface_decl || !property_clang_type_to_access.IsValid())
7651 return false;
7652
7653 clang::TypeSourceInfo *prop_type_source;
7654 if (ivar_decl)
7655 prop_type_source = clang_ast.getTrivialTypeSourceInfo(ivar_decl->getType());
7656 else
7657 prop_type_source = clang_ast.getTrivialTypeSourceInfo(
7658 ClangUtil::GetQualType(property_clang_type));
7659
7660 clang::ObjCPropertyDecl *property_decl =
7661 clang::ObjCPropertyDecl::CreateDeserialized(clang_ast, 0);
7662 property_decl->setDeclContext(class_interface_decl);
7663 property_decl->setDeclName(&clang_ast.Idents.get(property_name));
7664 property_decl->setType(ivar_decl
7665 ? ivar_decl->getType()
7666 : ClangUtil::GetQualType(property_clang_type),
7667 prop_type_source);
7668 SetMemberOwningModule(property_decl, class_interface_decl);
7669
7670 if (!property_decl)
7671 return false;
7672
7673 if (metadata)
7674 ast->SetMetadata(property_decl, *metadata);
7675
7676 class_interface_decl->addDecl(property_decl);
7677
7678 clang::Selector setter_sel, getter_sel;
7679
7680 if (property_setter_name) {
7681 std::string property_setter_no_colon(property_setter_name,
7682 strlen(property_setter_name) - 1);
7683 clang::IdentifierInfo *setter_ident =
7684 &clang_ast.Idents.get(property_setter_no_colon);
7685 setter_sel = clang_ast.Selectors.getSelector(1, &setter_ident);
7686 } else if (!(property_attributes & DW_APPLE_PROPERTY_readonly)) {
7687 std::string setter_sel_string("set");
7688 setter_sel_string.push_back(::toupper(property_name[0]));
7689 setter_sel_string.append(&property_name[1]);
7690 clang::IdentifierInfo *setter_ident =
7691 &clang_ast.Idents.get(setter_sel_string);
7692 setter_sel = clang_ast.Selectors.getSelector(1, &setter_ident);
7693 }
7694 property_decl->setSetterName(setter_sel);
7695 property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_setter);
7696
7697 if (property_getter_name != nullptr) {
7698 clang::IdentifierInfo *getter_ident =
7699 &clang_ast.Idents.get(property_getter_name);
7700 getter_sel = clang_ast.Selectors.getSelector(0, &getter_ident);
7701 } else {
7702 clang::IdentifierInfo *getter_ident = &clang_ast.Idents.get(property_name);
7703 getter_sel = clang_ast.Selectors.getSelector(0, &getter_ident);
7704 }
7705 property_decl->setGetterName(getter_sel);
7706 property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_getter);
7707
7708 if (ivar_decl)
7709 property_decl->setPropertyIvarDecl(ivar_decl);
7710
7711 if (property_attributes & DW_APPLE_PROPERTY_readonly)
7712 property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_readonly);
7713 if (property_attributes & DW_APPLE_PROPERTY_readwrite)
7714 property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_readwrite);
7715 if (property_attributes & DW_APPLE_PROPERTY_assign)
7716 property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_assign);
7717 if (property_attributes & DW_APPLE_PROPERTY_retain)
7718 property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_retain);
7719 if (property_attributes & DW_APPLE_PROPERTY_copy)
7720 property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_copy);
7721 if (property_attributes & DW_APPLE_PROPERTY_nonatomic)
7722 property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_nonatomic);
7723 if (property_attributes & ObjCPropertyAttribute::kind_nullability)
7724 property_decl->setPropertyAttributes(
7725 ObjCPropertyAttribute::kind_nullability);
7726 if (property_attributes & ObjCPropertyAttribute::kind_null_resettable)
7727 property_decl->setPropertyAttributes(
7728 ObjCPropertyAttribute::kind_null_resettable);
7729 if (property_attributes & ObjCPropertyAttribute::kind_class)
7730 property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_class);
7731
7732 const bool isInstance =
7733 (property_attributes & ObjCPropertyAttribute::kind_class) == 0;
7734
7735 clang::ObjCMethodDecl *getter = nullptr;
7736 if (!getter_sel.isNull())
7737 getter = isInstance ? class_interface_decl->lookupInstanceMethod(getter_sel)
7738 : class_interface_decl->lookupClassMethod(getter_sel);
7739 if (!getter_sel.isNull() && !getter) {
7740 const bool isVariadic = false;
7741 const bool isPropertyAccessor = true;
7742 const bool isSynthesizedAccessorStub = false;
7743 const bool isImplicitlyDeclared = true;
7744 const bool isDefined = false;
7745 const clang::ObjCMethodDecl::ImplementationControl impControl =
7746 clang::ObjCMethodDecl::None;
7747 const bool HasRelatedResultType = false;
7748
7749 getter = clang::ObjCMethodDecl::CreateDeserialized(clang_ast, 0);
7750 getter->setDeclName(getter_sel);
7751 getter->setReturnType(ClangUtil::GetQualType(property_clang_type_to_access));
7752 getter->setDeclContext(class_interface_decl);
7753 getter->setInstanceMethod(isInstance);
7754 getter->setVariadic(isVariadic);
7755 getter->setPropertyAccessor(isPropertyAccessor);
7756 getter->setSynthesizedAccessorStub(isSynthesizedAccessorStub);
7757 getter->setImplicit(isImplicitlyDeclared);
7758 getter->setDefined(isDefined);
7759 getter->setDeclImplementation(impControl);
7760 getter->setRelatedResultType(HasRelatedResultType);
7761 SetMemberOwningModule(getter, class_interface_decl);
7762
7763 if (getter) {
7764 if (metadata)
7765 ast->SetMetadata(getter, *metadata);
7766
7767 getter->setMethodParams(clang_ast, llvm::ArrayRef<clang::ParmVarDecl *>(),
7768 llvm::ArrayRef<clang::SourceLocation>());
7769 class_interface_decl->addDecl(getter);
7770 }
7771 }
7772 if (getter) {
7773 getter->setPropertyAccessor(true);
7774 property_decl->setGetterMethodDecl(getter);
7775 }
7776
7777 clang::ObjCMethodDecl *setter = nullptr;
7778 setter = isInstance ? class_interface_decl->lookupInstanceMethod(setter_sel)
7779 : class_interface_decl->lookupClassMethod(setter_sel);
7780 if (!setter_sel.isNull() && !setter) {
7781 clang::QualType result_type = clang_ast.VoidTy;
7782 const bool isVariadic = false;
7783 const bool isPropertyAccessor = true;
7784 const bool isSynthesizedAccessorStub = false;
7785 const bool isImplicitlyDeclared = true;
7786 const bool isDefined = false;
7787 const clang::ObjCMethodDecl::ImplementationControl impControl =
7788 clang::ObjCMethodDecl::None;
7789 const bool HasRelatedResultType = false;
7790
7791 setter = clang::ObjCMethodDecl::CreateDeserialized(clang_ast, 0);
7792 setter->setDeclName(setter_sel);
7793 setter->setReturnType(result_type);
7794 setter->setDeclContext(class_interface_decl);
7795 setter->setInstanceMethod(isInstance);
7796 setter->setVariadic(isVariadic);
7797 setter->setPropertyAccessor(isPropertyAccessor);
7798 setter->setSynthesizedAccessorStub(isSynthesizedAccessorStub);
7799 setter->setImplicit(isImplicitlyDeclared);
7800 setter->setDefined(isDefined);
7801 setter->setDeclImplementation(impControl);
7802 setter->setRelatedResultType(HasRelatedResultType);
7803 SetMemberOwningModule(setter, class_interface_decl);
7804
7805 if (setter) {
7806 if (metadata)
7807 ast->SetMetadata(setter, *metadata);
7808
7809 llvm::SmallVector<clang::ParmVarDecl *, 1> params;
7810 params.push_back(clang::ParmVarDecl::Create(
7811 clang_ast, setter, clang::SourceLocation(), clang::SourceLocation(),
7812 nullptr, // anonymous
7813 ClangUtil::GetQualType(property_clang_type_to_access), nullptr,
7814 clang::SC_Auto, nullptr));
7815
7816 setter->setMethodParams(clang_ast,
7817 llvm::ArrayRef<clang::ParmVarDecl *>(params),
7818 llvm::ArrayRef<clang::SourceLocation>());
7819
7820 class_interface_decl->addDecl(setter);
7821 }
7822 }
7823 if (setter) {
7824 setter->setPropertyAccessor(true);
7825 property_decl->setSetterMethodDecl(setter);
7826 }
7827
7828 return true;
7829}
7830
7831bool TypeSystemClang::IsObjCClassTypeAndHasIVars(const CompilerType &type,
7832 bool check_superclass) {
7833 clang::ObjCInterfaceDecl *class_interface_decl = GetAsObjCInterfaceDecl(type);
7834 if (class_interface_decl)
7835 return ObjCDeclHasIVars(class_interface_decl, check_superclass);
7836 return false;
7837}
7838
7839clang::ObjCMethodDecl *TypeSystemClang::AddMethodToObjCObjectType(
7840 const CompilerType &type,
7841 const char *name, // the full symbol name as seen in the symbol table
7842 // (lldb::opaque_compiler_type_t type, "-[NString
7843 // stringWithCString:]")
7844 const CompilerType &method_clang_type, lldb::AccessType access,
7845 bool is_artificial, bool is_variadic, bool is_objc_direct_call) {
7846 if (!type || !method_clang_type.IsValid())
7847 return nullptr;
7848
7849 clang::ObjCInterfaceDecl *class_interface_decl = GetAsObjCInterfaceDecl(type);
7850
7851 if (class_interface_decl == nullptr)
7852 return nullptr;
7853 TypeSystemClang *lldb_ast =
7854 llvm::dyn_cast<TypeSystemClang>(type.GetTypeSystem());
7855 if (lldb_ast == nullptr)
7856 return nullptr;
7857 clang::ASTContext &ast = lldb_ast->getASTContext();
7858
7859 const char *selector_start = ::strchr(name, ' ');
7860 if (selector_start == nullptr)
7861 return nullptr;
7862
7863 selector_start++;
7864 llvm::SmallVector<clang::IdentifierInfo *, 12> selector_idents;
7865
7866 size_t len = 0;
7867 const char *start;
7868
7869 unsigned num_selectors_with_args = 0;
7870 for (start = selector_start; start && *start != '\0' && *start != ']';
7871 start += len) {
7872 len = ::strcspn(start, ":]");
7873 bool has_arg = (start[len] == ':');
7874 if (has_arg)
7875 ++num_selectors_with_args;
7876 selector_idents.push_back(&ast.Idents.get(llvm::StringRef(start, len)));
7877 if (has_arg)
7878 len += 1;
7879 }
7880
7881 if (selector_idents.size() == 0)
7882 return nullptr;
7883
7884 clang::Selector method_selector = ast.Selectors.getSelector(
7885 num_selectors_with_args ? selector_idents.size() : 0,
7886 selector_idents.data());
7887
7888 clang::QualType method_qual_type(ClangUtil::GetQualType(method_clang_type));
7889
7890 // Populate the method decl with parameter decls
7891 const clang::Type *method_type(method_qual_type.getTypePtr());
7892
7893 if (method_type == nullptr)
7894 return nullptr;
7895
7896 const clang::FunctionProtoType *method_function_prototype(
7897 llvm::dyn_cast<clang::FunctionProtoType>(method_type));
7898
7899 if (!method_function_prototype)
7900 return nullptr;
7901
7902 const bool isInstance = (name[0] == '-');
7903 const bool isVariadic = is_variadic;
7904 const bool isPropertyAccessor = false;
7905 const bool isSynthesizedAccessorStub = false;
7906 /// Force this to true because we don't have source locations.
7907 const bool isImplicitlyDeclared = true;
7908 const bool isDefined = false;
7909 const clang::ObjCMethodDecl::ImplementationControl impControl =
7910 clang::ObjCMethodDecl::None;
7911 const bool HasRelatedResultType = false;
7912
7913 const unsigned num_args = method_function_prototype->getNumParams();
7914
7915 if (num_args != num_selectors_with_args)
7916 return nullptr; // some debug information is corrupt. We are not going to
7917 // deal with it.
7918
7919 auto *objc_method_decl = clang::ObjCMethodDecl::CreateDeserialized(ast, 0);
7920 objc_method_decl->setDeclName(method_selector);
7921 objc_method_decl->setReturnType(method_function_prototype->getReturnType());
7922 objc_method_decl->setDeclContext(
7923 lldb_ast->GetDeclContextForType(ClangUtil::GetQualType(type)));
7924 objc_method_decl->setInstanceMethod(isInstance);
7925 objc_method_decl->setVariadic(isVariadic);
7926 objc_method_decl->setPropertyAccessor(isPropertyAccessor);
7927 objc_method_decl->setSynthesizedAccessorStub(isSynthesizedAccessorStub);
7928 objc_method_decl->setImplicit(isImplicitlyDeclared);
7929 objc_method_decl->setDefined(isDefined);
7930 objc_method_decl->setDeclImplementation(impControl);
7931 objc_method_decl->setRelatedResultType(HasRelatedResultType);
7932 SetMemberOwningModule(objc_method_decl, class_interface_decl);
7933
7934 if (objc_method_decl == nullptr)
7935 return nullptr;
7936
7937 if (num_args > 0) {
7938 llvm::SmallVector<clang::ParmVarDecl *, 12> params;
7939
7940 for (unsigned param_index = 0; param_index < num_args; ++param_index) {
7941 params.push_back(clang::ParmVarDecl::Create(
7942 ast, objc_method_decl, clang::SourceLocation(),
7943 clang::SourceLocation(),
7944 nullptr, // anonymous
7945 method_function_prototype->getParamType(param_index), nullptr,
7946 clang::SC_Auto, nullptr));
7947 }
7948
7949 objc_method_decl->setMethodParams(
7950 ast, llvm::ArrayRef<clang::ParmVarDecl *>(params),
7951 llvm::ArrayRef<clang::SourceLocation>());
7952 }
7953
7954 if (is_objc_direct_call) {
7955 // Add a the objc_direct attribute to the declaration we generate that
7956 // we generate a direct method call for this ObjCMethodDecl.
7957 objc_method_decl->addAttr(
7958 clang::ObjCDirectAttr::CreateImplicit(ast, SourceLocation()));
7959 // Usually Sema is creating implicit parameters (e.g., self) when it
7960 // parses the method. We don't have a parsing Sema when we build our own
7961 // AST here so we manually need to create these implicit parameters to
7962 // make the direct call code generation happy.
7963 objc_method_decl->createImplicitParams(ast, class_interface_decl);
7964 }
7965
7966 class_interface_decl->addDecl(objc_method_decl);
7967
7968 VerifyDecl(objc_method_decl);
7969
7970 return objc_method_decl;
7971}
7972
7973bool TypeSystemClang::SetHasExternalStorage(lldb::opaque_compiler_type_t type,
7974 bool has_extern) {
7975 if (!type)
7976 return false;
7977
7978 clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type)));
7979
7980 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
7981 switch (type_class) {
7982 case clang::Type::Record: {
7983 clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl();
7984 if (cxx_record_decl) {
7985 cxx_record_decl->setHasExternalLexicalStorage(has_extern);
7986 cxx_record_decl->setHasExternalVisibleStorage(has_extern);
7987 return true;
7988 }
7989 } break;
7990
7991 case clang::Type::Enum: {
7992 clang::EnumDecl *enum_decl =
7993 llvm::cast<clang::EnumType>(qual_type)->getDecl();
7994 if (enum_decl) {
7995 enum_decl->setHasExternalLexicalStorage(has_extern);
7996 enum_decl->setHasExternalVisibleStorage(has_extern);
7997 return true;
7998 }
7999 } break;
8000
8001 case clang::Type::ObjCObject:
8002 case clang::Type::ObjCInterface: {
8003 const clang::ObjCObjectType *objc_class_type =
8004 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
8005 assert(objc_class_type);
8006 if (objc_class_type) {
8007 clang::ObjCInterfaceDecl *class_interface_decl =
8008 objc_class_type->getInterface();
8009
8010 if (class_interface_decl) {
8011 class_interface_decl->setHasExternalLexicalStorage(has_extern);
8012 class_interface_decl->setHasExternalVisibleStorage(has_extern);
8013 return true;
8014 }
8015 }
8016 } break;
8017
8018 default:
8019 break;
8020 }
8021 return false;
8022}
8023
8024#pragma mark TagDecl
8025
8026bool TypeSystemClang::StartTagDeclarationDefinition(const CompilerType &type) {
8027 clang::QualType qual_type(ClangUtil::GetQualType(type));
8028 if (!qual_type.isNull()) {
8029 const clang::TagType *tag_type = qual_type->getAs<clang::TagType>();
8030 if (tag_type) {
8031 clang::TagDecl *tag_decl = tag_type->getDecl();
8032 if (tag_decl) {
8033 tag_decl->startDefinition();
8034 return true;
8035 }
8036 }
8037
8038 const clang::ObjCObjectType *object_type =
8039 qual_type->getAs<clang::ObjCObjectType>();
8040 if (object_type) {
8041 clang::ObjCInterfaceDecl *interface_decl = object_type->getInterface();
8042 if (interface_decl) {
8043 interface_decl->startDefinition();
8044 return true;
8045 }
8046 }
8047 }
8048 return false;
8049}
8050
8051bool TypeSystemClang::CompleteTagDeclarationDefinition(
8052 const CompilerType &type) {
8053 clang::QualType qual_type(ClangUtil::GetQualType(type));
8054 if (qual_type.isNull())
8055 return false;
8056
8057 // Make sure we use the same methodology as
8058 // TypeSystemClang::StartTagDeclarationDefinition() as to how we start/end
8059 // the definition.
8060 const clang::TagType *tag_type = qual_type->getAs<clang::TagType>();
8061 if (tag_type) {
8062 clang::TagDecl *tag_decl = tag_type->getDecl();
8063
8064 if (auto *cxx_record_decl = llvm::dyn_cast<CXXRecordDecl>(tag_decl)) {
8065 // If we have a move constructor declared but no copy constructor we
8066 // need to explicitly mark it as deleted. Usually Sema would do this for
8067 // us in Sema::DeclareImplicitCopyConstructor but we don't have a Sema
8068 // when building an AST from debug information.
8069 // See also:
8070 // C++11 [class.copy]p7, p18:
8071 // If the class definition declares a move constructor or move assignment
8072 // operator, an implicitly declared copy constructor or copy assignment
8073 // operator is defined as deleted.
8074 if (cxx_record_decl->hasUserDeclaredMoveConstructor() ||
8075 cxx_record_decl->hasUserDeclaredMoveAssignment()) {
8076 if (cxx_record_decl->needsImplicitCopyConstructor())
8077 cxx_record_decl->setImplicitCopyConstructorIsDeleted();
8078 if (cxx_record_decl->needsImplicitCopyAssignment())
8079 cxx_record_decl->setImplicitCopyAssignmentIsDeleted();
8080 }
8081
8082 if (!cxx_record_decl->isCompleteDefinition())
8083 cxx_record_decl->completeDefinition();
8084 cxx_record_decl->setHasLoadedFieldsFromExternalStorage(true);
8085 cxx_record_decl->setHasExternalLexicalStorage(false);
8086 cxx_record_decl->setHasExternalVisibleStorage(false);
8087 return true;
8088 }
8089 }
8090
8091 const clang::EnumType *enutype = qual_type->getAs<clang::EnumType>();
8092
8093 if (!enutype)
8094 return false;
8095 clang::EnumDecl *enum_decl = enutype->getDecl();
8096
8097 if (enum_decl->isCompleteDefinition())
8098 return true;
8099
8100 TypeSystemClang *lldb_ast =
8101 llvm::dyn_cast<TypeSystemClang>(type.GetTypeSystem());
8102 if (lldb_ast == nullptr)
8103 return false;
8104 clang::ASTContext &ast = lldb_ast->getASTContext();
8105
8106 /// TODO This really needs to be fixed.
8107
8108 QualType integer_type(enum_decl->getIntegerType());
8109 if (!integer_type.isNull()) {
8110 unsigned NumPositiveBits = 1;
8111 unsigned NumNegativeBits = 0;
8112
8113 clang::QualType promotion_qual_type;
8114 // If the enum integer type is less than an integer in bit width,
8115 // then we must promote it to an integer size.
8116 if (ast.getTypeSize(enum_decl->getIntegerType()) <
8117 ast.getTypeSize(ast.IntTy)) {
8118 if (enum_decl->getIntegerType()->isSignedIntegerType())
8119 promotion_qual_type = ast.IntTy;
8120 else
8121 promotion_qual_type = ast.UnsignedIntTy;
8122 } else
8123 promotion_qual_type = enum_decl->getIntegerType();
8124
8125 enum_decl->completeDefinition(enum_decl->getIntegerType(),
8126 promotion_qual_type, NumPositiveBits,
8127 NumNegativeBits);
8128 }
8129 return true;
8130}
8131
8132clang::EnumConstantDecl *TypeSystemClang::AddEnumerationValueToEnumerationType(
8133 const CompilerType &enum_type, const Declaration &decl, const char *name,
8134 const llvm::APSInt &value) {
8135
8136 if (!enum_type || ConstString(name).IsEmpty())
8137 return nullptr;
8138
8139 lldbassert(enum_type.GetTypeSystem() == static_cast<TypeSystem *>(this));
8140
8141 lldb::opaque_compiler_type_t enum_opaque_compiler_type =
8142 enum_type.GetOpaqueQualType();
8143
8144 if (!enum_opaque_compiler_type)
8145 return nullptr;
8146
8147 clang::QualType enum_qual_type(
8148 GetCanonicalQualType(enum_opaque_compiler_type));
8149
8150 const clang::Type *clang_type = enum_qual_type.getTypePtr();
8151
8152 if (!clang_type)
8153 return nullptr;
8154
8155 const clang::EnumType *enutype = llvm::dyn_cast<clang::EnumType>(clang_type);
8156
8157 if (!enutype)
8158 return nullptr;
8159
8160 clang::EnumConstantDecl *enumerator_decl =
8161 clang::EnumConstantDecl::CreateDeserialized(getASTContext(), 0);
8162 enumerator_decl->setDeclContext(enutype->getDecl());
8163 if (name && name[0])
8164 enumerator_decl->setDeclName(&getASTContext().Idents.get(name));
8165 enumerator_decl->setType(clang::QualType(enutype, 0));
8166 enumerator_decl->setInitVal(value);
8167 SetMemberOwningModule(enumerator_decl, enutype->getDecl());
8168
8169 if (!enumerator_decl)
8170 return nullptr;
8171
8172 enutype->getDecl()->addDecl(enumerator_decl);
8173
8174 VerifyDecl(enumerator_decl);
8175 return enumerator_decl;
8176}
8177
8178clang::EnumConstantDecl *TypeSystemClang::AddEnumerationValueToEnumerationType(
8179 const CompilerType &enum_type, const Declaration &decl, const char *name,
8180 int64_t enum_value, uint32_t enum_value_bit_size) {
8181 CompilerType underlying_type = GetEnumerationIntegerType(enum_type);
8182 bool is_signed = false;
8183 underlying_type.IsIntegerType(is_signed);
8184
8185 llvm::APSInt value(enum_value_bit_size, is_signed);
8186 value = enum_value;
8187
8188 return AddEnumerationValueToEnumerationType(enum_type, decl, name, value);
8189}
8190
8191CompilerType TypeSystemClang::GetEnumerationIntegerType(CompilerType type) {
8192 clang::QualType qt(ClangUtil::GetQualType(type));
8193 const clang::Type *clang_type = qt.getTypePtrOrNull();
8194 const auto *enum_type = llvm::dyn_cast_or_null<clang::EnumType>(clang_type);
8195 if (!enum_type)
8196 return CompilerType();
8197
8198 return GetType(enum_type->getDecl()->getIntegerType());
8199}
8200
8201CompilerType
8202TypeSystemClang::CreateMemberPointerType(const CompilerType &type,
8203 const CompilerType &pointee_type) {
8204 if (type && pointee_type.IsValid() &&
8205 type.GetTypeSystem() == pointee_type.GetTypeSystem()) {
8206 TypeSystemClang *ast =
8207 llvm::dyn_cast<TypeSystemClang>(type.GetTypeSystem());
8208 if (!ast)
8209 return CompilerType();
8210 return ast->GetType(ast->getASTContext().getMemberPointerType(
8211 ClangUtil::GetQualType(pointee_type),
8212 ClangUtil::GetQualType(type).getTypePtr()));
8213 }
8214 return CompilerType();
8215}
8216
8217// Dumping types
8218#define DEPTH_INCREMENT 2
8219
8220#ifndef NDEBUG
8221LLVM_DUMP_METHOD void
8222TypeSystemClang::dump(lldb::opaque_compiler_type_t type) const {
8223 if (!type)
8224 return;
8225 clang::QualType qual_type(GetQualType(type));
8226 qual_type.dump();
8227}
8228#endif
8229
8230void TypeSystemClang::Dump(Stream &s) {
8231 Decl *tu = Decl::castFromDeclContext(GetTranslationUnitDecl());
8232 tu->dump(s.AsRawOstream());
8233}
8234
8235void TypeSystemClang::DumpFromSymbolFile(Stream &s,
8236 llvm::StringRef symbol_name) {
8237 SymbolFile *symfile = GetSymbolFile();
8238
8239 if (!symfile)
8240 return;
8241
8242 lldb_private::TypeList type_list;
8243 symfile->GetTypes(nullptr, eTypeClassAny, type_list);
8244 size_t ntypes = type_list.GetSize();
8245
8246 for (size_t i = 0; i < ntypes; ++i) {
8247 TypeSP type = type_list.GetTypeAtIndex(i);
8248
8249 if (!symbol_name.empty())
8250 if (symbol_name != type->GetName().GetStringRef())
8251 continue;
8252
8253 s << type->GetName().AsCString() << "\n";
8254
8255 CompilerType full_type = type->GetFullCompilerType();
8256 if (clang::TagDecl *tag_decl = GetAsTagDecl(full_type)) {
8257 tag_decl->dump(s.AsRawOstream());
8258 continue;
8259 }
8260 if (clang::TypedefNameDecl *typedef_decl = GetAsTypedefDecl(full_type)) {
8261 typedef_decl->dump(s.AsRawOstream());
8262 continue;
8263 }
8264 if (auto *objc_obj = llvm::dyn_cast<clang::ObjCObjectType>(
8265 ClangUtil::GetQualType(full_type).getTypePtr())) {
8266 if (clang::ObjCInterfaceDecl *interface_decl = objc_obj->getInterface()) {
8267 interface_decl->dump(s.AsRawOstream());
8268 continue;
8269 }
8270 }
8271 GetCanonicalQualType(full_type.GetOpaqueQualType())
8272 .dump(s.AsRawOstream(), getASTContext());
8273 }
8274}
8275
8276void TypeSystemClang::DumpValue(
8277 lldb::opaque_compiler_type_t type, ExecutionContext *exe_ctx, Stream *s,
8278 lldb::Format format, const lldb_private::DataExtractor &data,
8279 lldb::offset_t data_byte_offset, size_t data_byte_size,
8280 uint32_t bitfield_bit_size, uint32_t bitfield_bit_offset, bool show_types,
8281 bool show_summary, bool verbose, uint32_t depth) {
8282 if (!type)
8283 return;
8284
8285 clang::QualType qual_type(GetQualType(type));
8286 switch (qual_type->getTypeClass()) {
8287 case clang::Type::Record:
8288 if (GetCompleteType(type)) {
8289 const clang::RecordType *record_type =
8290 llvm::cast<clang::RecordType>(qual_type.getTypePtr());
8291 const clang::RecordDecl *record_decl = record_type->getDecl();
8292 assert(record_decl);
8293 uint32_t field_bit_offset = 0;
8294 uint32_t field_byte_offset = 0;
8295 const clang::ASTRecordLayout &record_layout =
8296 getASTContext().getASTRecordLayout(record_decl);
8297 uint32_t child_idx = 0;
8298
8299 const clang::CXXRecordDecl *cxx_record_decl =
8300 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl);
8301 if (cxx_record_decl) {
8302 // We might have base classes to print out first
8303 clang::CXXRecordDecl::base_class_const_iterator base_class,
8304 base_class_end;
8305 for (base_class = cxx_record_decl->bases_begin(),
8306 base_class_end = cxx_record_decl->bases_end();
8307 base_class != base_class_end; ++base_class) {
8308 const clang::CXXRecordDecl *base_class_decl =
8309 llvm::cast<clang::CXXRecordDecl>(
8310 base_class->getType()->getAs<clang::RecordType>()->getDecl());
8311
8312 // Skip empty base classes
8313 if (!verbose && !TypeSystemClang::RecordHasFields(base_class_decl))
8314 continue;
8315
8316 if (base_class->isVirtual())
8317 field_bit_offset =
8318 record_layout.getVBaseClassOffset(base_class_decl)
8319 .getQuantity() *
8320 8;
8321 else
8322 field_bit_offset = record_layout.getBaseClassOffset(base_class_decl)
8323 .getQuantity() *
8324 8;
8325 field_byte_offset = field_bit_offset / 8;
8326 assert(field_bit_offset % 8 == 0);
8327 if (child_idx == 0)
8328 s->PutChar('{');
8329 else
8330 s->PutChar(',');
8331
8332 clang::QualType base_class_qual_type = base_class->getType();
8333 std::string base_class_type_name(base_class_qual_type.getAsString());
8334
8335 // Indent and print the base class type name
8336 s->Format("\n{0}{1}", llvm::fmt_repeat(" ", depth + DEPTH_INCREMENT),
8337 base_class_type_name);
8338
8339 clang::TypeInfo base_class_type_info =
8340 getASTContext().getTypeInfo(base_class_qual_type);
8341
8342 // Dump the value of the member
8343 CompilerType base_clang_type = GetType(base_class_qual_type);
8344 base_clang_type.DumpValue(
8345 exe_ctx,
8346 s, // Stream to dump to
8347 base_clang_type
8348 .GetFormat(), // The format with which to display the member
8349 data, // Data buffer containing all bytes for this type
8350 data_byte_offset + field_byte_offset, // Offset into "data" where
8351 // to grab value from
8352 base_class_type_info.Width / 8, // Size of this type in bytes
8353 0, // Bitfield bit size
8354 0, // Bitfield bit offset
8355 show_types, // Boolean indicating if we should show the variable
8356 // types
8357 show_summary, // Boolean indicating if we should show a summary
8358 // for the current type
8359 verbose, // Verbose output?
8360 depth + DEPTH_INCREMENT); // Scope depth for any types that have
8361 // children
8362
8363 ++child_idx;
8364 }
8365 }
8366 uint32_t field_idx = 0;
8367 clang::RecordDecl::field_iterator field, field_end;
8368 for (field = record_decl->field_begin(),
8369 field_end = record_decl->field_end();
8370 field != field_end; ++field, ++field_idx, ++child_idx) {
8371 // Print the starting squiggly bracket (if this is the first member) or
8372 // comma (for member 2 and beyond) for the struct/union/class member.
8373 if (child_idx == 0)
8374 s->PutChar('{');
8375 else
8376 s->PutChar(',');
8377
8378 // Indent
8379 s->Printf("\n%*s", depth + DEPTH_INCREMENT, "");
8380
8381 clang::QualType field_type = field->getType();
8382 // Print the member type if requested
8383 // Figure out the type byte size (field_type_info.first) and alignment
8384 // (field_type_info.second) from the AST context.
8385 clang::TypeInfo field_type_info =
8386 getASTContext().getTypeInfo(field_type);
8387 assert(field_idx < record_layout.getFieldCount());
8388 // Figure out the field offset within the current struct/union/class
8389 // type
8390 field_bit_offset = record_layout.getFieldOffset(field_idx);
8391 field_byte_offset = field_bit_offset / 8;
8392 uint32_t field_bitfield_bit_size = 0;
8393 uint32_t field_bitfield_bit_offset = 0;
8394 if (FieldIsBitfield(*field, field_bitfield_bit_size))
8395 field_bitfield_bit_offset = field_bit_offset % 8;
8396
8397 if (show_types) {
8398 std::string field_type_name(field_type.getAsString());
8399 if (field_bitfield_bit_size > 0)
8400 s->Printf("(%s:%u) ", field_type_name.c_str(),
8401 field_bitfield_bit_size);
8402 else
8403 s->Printf("(%s) ", field_type_name.c_str());
8404 }
8405 // Print the member name and equal sign
8406 s->Printf("%s = ", field->getNameAsString().c_str());
8407
8408 // Dump the value of the member
8409 CompilerType field_clang_type = GetType(field_type);
8410 field_clang_type.DumpValue(
8411 exe_ctx,
8412 s, // Stream to dump to
8413 field_clang_type
8414 .GetFormat(), // The format with which to display the member
8415 data, // Data buffer containing all bytes for this type
8416 data_byte_offset + field_byte_offset, // Offset into "data" where to
8417 // grab value from
8418 field_type_info.Width / 8, // Size of this type in bytes
8419 field_bitfield_bit_size, // Bitfield bit size
8420 field_bitfield_bit_offset, // Bitfield bit offset
8421 show_types, // Boolean indicating if we should show the variable
8422 // types
8423 show_summary, // Boolean indicating if we should show a summary for
8424 // the current type
8425 verbose, // Verbose output?
8426 depth + DEPTH_INCREMENT); // Scope depth for any types that have
8427 // children
8428 }
8429
8430 // Indent the trailing squiggly bracket
8431 if (child_idx > 0)
8432 s->Printf("\n%*s}", depth, "");
8433 }
8434 return;
8435
8436 case clang::Type::Enum:
8437 if (GetCompleteType(type)) {
8438 const clang::EnumType *enutype =
8439 llvm::cast<clang::EnumType>(qual_type.getTypePtr());
8440 const clang::EnumDecl *enum_decl = enutype->getDecl();
8441 assert(enum_decl);
8442 clang::EnumDecl::enumerator_iterator enum_pos, enum_end_pos;
8443 lldb::offset_t offset = data_byte_offset;
8444 const int64_t enum_value = data.GetMaxU64Bitfield(
8445 &offset, data_byte_size, bitfield_bit_size, bitfield_bit_offset);
8446 for (enum_pos = enum_decl->enumerator_begin(),
8447 enum_end_pos = enum_decl->enumerator_end();
8448 enum_pos != enum_end_pos; ++enum_pos) {
8449 if (enum_pos->getInitVal() == enum_value) {
8450 s->Printf("%s", enum_pos->getNameAsString().c_str());
8451 return;
8452 }
8453 }
8454 // If we have gotten here we didn't get find the enumerator in the enum
8455 // decl, so just print the integer.
8456 s->Printf("%" PRIi64, enum_value);
8457 }
8458 return;
8459
8460 case clang::Type::ConstantArray: {
8461 const clang::ConstantArrayType *array =
8462 llvm::cast<clang::ConstantArrayType>(qual_type.getTypePtr());
8463 bool is_array_of_characters = false;
8464 clang::QualType element_qual_type = array->getElementType();
8465
8466 const clang::Type *canonical_type =
8467 element_qual_type->getCanonicalTypeInternal().getTypePtr();
8468 if (canonical_type)
8469 is_array_of_characters = canonical_type->isCharType();
8470
8471 const uint64_t element_count = array->getSize().getLimitedValue();
8472
8473 clang::TypeInfo field_type_info =
8474 getASTContext().getTypeInfo(element_qual_type);
8475
8476 uint32_t element_idx = 0;
8477 uint32_t element_offset = 0;
8478 uint64_t element_byte_size = field_type_info.Width / 8;
8479 uint32_t element_stride = element_byte_size;
8480
8481 if (is_array_of_characters) {
8482 s->PutChar('"');
8483 DumpDataExtractor(data, s, data_byte_offset, lldb::eFormatChar,
8484 element_byte_size, element_count, UINT32_MAX,
8485 LLDB_INVALID_ADDRESS, 0, 0);
8486 s->PutChar('"');
8487 return;
8488 } else {
8489 CompilerType element_clang_type = GetType(element_qual_type);
8490 lldb::Format element_format = element_clang_type.GetFormat();
8491
8492 for (element_idx = 0; element_idx < element_count; ++element_idx) {
8493 // Print the starting squiggly bracket (if this is the first member) or
8494 // comman (for member 2 and beyong) for the struct/union/class member.
8495 if (element_idx == 0)
8496 s->PutChar('{');
8497 else
8498 s->PutChar(',');
8499
8500 // Indent and print the index
8501 s->Printf("\n%*s[%u] ", depth + DEPTH_INCREMENT, "", element_idx);
8502
8503 // Figure out the field offset within the current struct/union/class
8504 // type
8505 element_offset = element_idx * element_stride;
8506
8507 // Dump the value of the member
8508 element_clang_type.DumpValue(
8509 exe_ctx,
8510 s, // Stream to dump to
8511 element_format, // The format with which to display the element
8512 data, // Data buffer containing all bytes for this type
8513 data_byte_offset +
8514 element_offset, // Offset into "data" where to grab value from
8515 element_byte_size, // Size of this type in bytes
8516 0, // Bitfield bit size
8517 0, // Bitfield bit offset
8518 show_types, // Boolean indicating if we should show the variable
8519 // types
8520 show_summary, // Boolean indicating if we should show a summary for
8521 // the current type
8522 verbose, // Verbose output?
8523 depth + DEPTH_INCREMENT); // Scope depth for any types that have
8524 // children
8525 }
8526
8527 // Indent the trailing squiggly bracket
8528 if (element_idx > 0)
8529 s->Printf("\n%*s}", depth, "");
8530 }
8531 }
8532 return;
8533
8534 case clang::Type::Typedef: {
8535 clang::QualType typedef_qual_type =
8536 llvm::cast<clang::TypedefType>(qual_type)
8537 ->getDecl()
8538 ->getUnderlyingType();
8539
8540 CompilerType typedef_clang_type = GetType(typedef_qual_type);
8541 lldb::Format typedef_format = typedef_clang_type.GetFormat();
8542 clang::TypeInfo typedef_type_info =
8543 getASTContext().getTypeInfo(typedef_qual_type);
8544 uint64_t typedef_byte_size = typedef_type_info.Width / 8;
8545
8546 return typedef_clang_type.DumpValue(
8547 exe_ctx,
8548 s, // Stream to dump to
8549 typedef_format, // The format with which to display the element
8550 data, // Data buffer containing all bytes for this type
8551 data_byte_offset, // Offset into "data" where to grab value from
8552 typedef_byte_size, // Size of this type in bytes
8553 bitfield_bit_size, // Bitfield bit size
8554 bitfield_bit_offset, // Bitfield bit offset
8555 show_types, // Boolean indicating if we should show the variable types
8556 show_summary, // Boolean indicating if we should show a summary for the
8557 // current type
8558 verbose, // Verbose output?
8559 depth); // Scope depth for any types that have children
8560 } break;
8561
8562 case clang::Type::Auto: {
8563 clang::QualType elaborated_qual_type =
8564 llvm::cast<clang::AutoType>(qual_type)->getDeducedType();
8565 CompilerType elaborated_clang_type = GetType(elaborated_qual_type);
8566 lldb::Format elaborated_format = elaborated_clang_type.GetFormat();
8567 clang::TypeInfo elaborated_type_info =
8568 getASTContext().getTypeInfo(elaborated_qual_type);
8569 uint64_t elaborated_byte_size = elaborated_type_info.Width / 8;
8570
8571 return elaborated_clang_type.DumpValue(
8572 exe_ctx,
8573 s, // Stream to dump to
8574 elaborated_format, // The format with which to display the element
8575 data, // Data buffer containing all bytes for this type
8576 data_byte_offset, // Offset into "data" where to grab value from
8577 elaborated_byte_size, // Size of this type in bytes
8578 bitfield_bit_size, // Bitfield bit size
8579 bitfield_bit_offset, // Bitfield bit offset
8580 show_types, // Boolean indicating if we should show the variable types
8581 show_summary, // Boolean indicating if we should show a summary for the
8582 // current type
8583 verbose, // Verbose output?
8584 depth); // Scope depth for any types that have children
8585 } break;
8586
8587 case clang::Type::Elaborated: {
8588 clang::QualType elaborated_qual_type =
8589 llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType();
8590 CompilerType elaborated_clang_type = GetType(elaborated_qual_type);
8591 lldb::Format elaborated_format = elaborated_clang_type.GetFormat();
8592 clang::TypeInfo elaborated_type_info =
8593 getASTContext().getTypeInfo(elaborated_qual_type);
8594 uint64_t elaborated_byte_size = elaborated_type_info.Width / 8;
8595
8596 return elaborated_clang_type.DumpValue(
8597 exe_ctx,
8598 s, // Stream to dump to
8599 elaborated_format, // The format with which to display the element
8600 data, // Data buffer containing all bytes for this type
8601 data_byte_offset, // Offset into "data" where to grab value from
8602 elaborated_byte_size, // Size of this type in bytes
8603 bitfield_bit_size, // Bitfield bit size
8604 bitfield_bit_offset, // Bitfield bit offset
8605 show_types, // Boolean indicating if we should show the variable types
8606 show_summary, // Boolean indicating if we should show a summary for the
8607 // current type
8608 verbose, // Verbose output?
8609 depth); // Scope depth for any types that have children
8610 } break;
8611
8612 case clang::Type::Paren: {
8613 clang::QualType desugar_qual_type =
8614 llvm::cast<clang::ParenType>(qual_type)->desugar();
8615 CompilerType desugar_clang_type = GetType(desugar_qual_type);
8616
8617 lldb::Format desugar_format = desugar_clang_type.GetFormat();
8618 clang::TypeInfo desugar_type_info =
8619 getASTContext().getTypeInfo(desugar_qual_type);
8620 uint64_t desugar_byte_size = desugar_type_info.Width / 8;
8621
8622 return desugar_clang_type.DumpValue(
8623 exe_ctx,
8624 s, // Stream to dump to
8625 desugar_format, // The format with which to display the element
8626 data, // Data buffer containing all bytes for this type
8627 data_byte_offset, // Offset into "data" where to grab value from
8628 desugar_byte_size, // Size of this type in bytes
8629 bitfield_bit_size, // Bitfield bit size
8630 bitfield_bit_offset, // Bitfield bit offset
8631 show_types, // Boolean indicating if we should show the variable types
8632 show_summary, // Boolean indicating if we should show a summary for the
8633 // current type
8634 verbose, // Verbose output?
8635 depth); // Scope depth for any types that have children
8636 } break;
8637
8638 default:
8639 // We are down to a scalar type that we just need to display.
8640 DumpDataExtractor(data, s, data_byte_offset, format, data_byte_size, 1,
8641 UINT32_MAX, LLDB_INVALID_ADDRESS, bitfield_bit_size,
8642 bitfield_bit_offset);
8643
8644 if (show_summary)
8645 DumpSummary(type, exe_ctx, s, data, data_byte_offset, data_byte_size);
8646 break;
8647 }
8648}
8649
8650static bool DumpEnumValue(const clang::QualType &qual_type, Stream *s,
8651 const DataExtractor &data, lldb::offset_t byte_offset,
8652 size_t byte_size, uint32_t bitfield_bit_offset,
8653 uint32_t bitfield_bit_size) {
8654 const clang::EnumType *enutype =
8655 llvm::cast<clang::EnumType>(qual_type.getTypePtr());
8656 const clang::EnumDecl *enum_decl = enutype->getDecl();
8657 assert(enum_decl);
8658 lldb::offset_t offset = byte_offset;
8659 const uint64_t enum_svalue = data.GetMaxS64Bitfield(
8660 &offset, byte_size, bitfield_bit_size, bitfield_bit_offset);
8661 bool can_be_bitfield = true;
8662 uint64_t covered_bits = 0;
8663 int num_enumerators = 0;
8664
8665 // Try to find an exact match for the value.
8666 // At the same time, we're applying a heuristic to determine whether we want
8667 // to print this enum as a bitfield. We're likely dealing with a bitfield if
8668 // every enumerator is either a one bit value or a superset of the previous
8669 // enumerators. Also 0 doesn't make sense when the enumerators are used as
8670 // flags.
8671 for (auto *enumerator : enum_decl->enumerators()) {
8672 uint64_t val = enumerator->getInitVal().getSExtValue();
8673 val = llvm::SignExtend64(val, 8*byte_size);
8674 if (llvm::countPopulation(val) != 1 && (val & ~covered_bits) != 0)
8675 can_be_bitfield = false;
8676 covered_bits |= val;
8677 ++num_enumerators;
8678 if (val == enum_svalue) {
8679 // Found an exact match, that's all we need to do.
8680 s->PutCString(enumerator->getNameAsString());
8681 return true;
8682 }
8683 }
8684
8685 // Unsigned values make more sense for flags.
8686 offset = byte_offset;
8687 const uint64_t enum_uvalue = data.GetMaxU64Bitfield(
8688 &offset, byte_size, bitfield_bit_size, bitfield_bit_offset);
8689
8690 // No exact match, but we don't think this is a bitfield. Print the value as
8691 // decimal.
8692 if (!can_be_bitfield) {
8693 if (qual_type->isSignedIntegerOrEnumerationType())
8694 s->Printf("%" PRIi64, enum_svalue);
8695 else
8696 s->Printf("%" PRIu64, enum_uvalue);
8697 return true;
8698 }
8699
8700 uint64_t remaining_value = enum_uvalue;
8701 std::vector<std::pair<uint64_t, llvm::StringRef>> values;
8702 values.reserve(num_enumerators);
8703 for (auto *enumerator : enum_decl->enumerators())
8704 if (auto val = enumerator->getInitVal().getZExtValue())
8705 values.emplace_back(val, enumerator->getName());
8706
8707 // Sort in reverse order of the number of the population count, so that in
8708 // `enum {A, B, ALL = A|B }` we visit ALL first. Use a stable sort so that
8709 // A | C where A is declared before C is displayed in this order.
8710 std::stable_sort(values.begin(), values.end(), [](const auto &a, const auto &b) {
8711 return llvm::countPopulation(a.first) > llvm::countPopulation(b.first);
8712 });
8713
8714 for (const auto &val : values) {
8715 if ((remaining_value & val.first) != val.first)
8716 continue;
8717 remaining_value &= ~val.first;
8718 s->PutCString(val.second);
8719 if (remaining_value)
8720 s->PutCString(" | ");
8721 }
8722
8723 // If there is a remainder that is not covered by the value, print it as hex.
8724 if (remaining_value)
8725 s->Printf("0x%" PRIx64, remaining_value);
8726
8727 return true;
8728}
8729
8730bool TypeSystemClang::DumpTypeValue(
8731 lldb::opaque_compiler_type_t type, Stream *s, lldb::Format format,
8732 const lldb_private::DataExtractor &data, lldb::offset_t byte_offset,
8733 size_t byte_size, uint32_t bitfield_bit_size, uint32_t bitfield_bit_offset,
8734 ExecutionContextScope *exe_scope) {
8735 if (!type)
8736 return false;
8737 if (IsAggregateType(type)) {
8738 return false;
8739 } else {
8740 clang::QualType qual_type(GetQualType(type));
8741
8742 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
8743
8744 if (type_class == clang::Type::Elaborated) {
8745 qual_type = llvm::cast<clang::ElaboratedType>(qual_type)->getNamedType();
8746 return DumpTypeValue(qual_type.getAsOpaquePtr(), s, format, data, byte_offset, byte_size,
8747 bitfield_bit_size, bitfield_bit_offset, exe_scope);
8748 }
8749
8750 switch (type_class) {
8751 case clang::Type::Typedef: {
8752 clang::QualType typedef_qual_type =
8753 llvm::cast<clang::TypedefType>(qual_type)
8754 ->getDecl()
8755 ->getUnderlyingType();
8756 CompilerType typedef_clang_type = GetType(typedef_qual_type);
8757 if (format == eFormatDefault)
8758 format = typedef_clang_type.GetFormat();
8759 clang::TypeInfo typedef_type_info =
8760 getASTContext().getTypeInfo(typedef_qual_type);
8761 uint64_t typedef_byte_size = typedef_type_info.Width / 8;
8762
8763 return typedef_clang_type.DumpTypeValue(
8764 s,
8765 format, // The format with which to display the element
8766 data, // Data buffer containing all bytes for this type
8767 byte_offset, // Offset into "data" where to grab value from
8768 typedef_byte_size, // Size of this type in bytes
8769 bitfield_bit_size, // Size in bits of a bitfield value, if zero don't
8770 // treat as a bitfield
8771 bitfield_bit_offset, // Offset in bits of a bitfield value if
8772 // bitfield_bit_size != 0
8773 exe_scope);
8774 } break;
8775
8776 case clang::Type::Enum:
8777 // If our format is enum or default, show the enumeration value as its
8778 // enumeration string value, else just display it as requested.
8779 if ((format == eFormatEnum || format == eFormatDefault) &&
8780 GetCompleteType(type))
8781 return DumpEnumValue(qual_type, s, data, byte_offset, byte_size,
8782 bitfield_bit_offset, bitfield_bit_size);
8783 // format was not enum, just fall through and dump the value as
8784 // requested....
8785 LLVM_FALLTHROUGH;
8786
8787 default:
8788 // We are down to a scalar type that we just need to display.
8789 {
8790 uint32_t item_count = 1;
8791 // A few formats, we might need to modify our size and count for
8792 // depending
8793 // on how we are trying to display the value...
8794 switch (format) {
8795 default:
8796 case eFormatBoolean:
8797 case eFormatBinary:
8798 case eFormatComplex:
8799 case eFormatCString: // NULL terminated C strings
8800 case eFormatDecimal:
8801 case eFormatEnum:
8802 case eFormatHex:
8803 case eFormatHexUppercase:
8804 case eFormatFloat:
8805 case eFormatOctal:
8806 case eFormatOSType:
8807 case eFormatUnsigned:
8808 case eFormatPointer:
8809 case eFormatVectorOfChar:
8810 case eFormatVectorOfSInt8:
8811 case eFormatVectorOfUInt8:
8812 case eFormatVectorOfSInt16:
8813 case eFormatVectorOfUInt16:
8814 case eFormatVectorOfSInt32:
8815 case eFormatVectorOfUInt32:
8816 case eFormatVectorOfSInt64:
8817 case eFormatVectorOfUInt64:
8818 case eFormatVectorOfFloat32:
8819 case eFormatVectorOfFloat64:
8820 case eFormatVectorOfUInt128:
8821 break;
8822
8823 case eFormatChar:
8824 case eFormatCharPrintable:
8825 case eFormatCharArray:
8826 case eFormatBytes:
8827 case eFormatBytesWithASCII:
8828 item_count = byte_size;
8829 byte_size = 1;
8830 break;
8831
8832 case eFormatUnicode16:
8833 item_count = byte_size / 2;
8834 byte_size = 2;
8835 break;
8836
8837 case eFormatUnicode32:
8838 item_count = byte_size / 4;
8839 byte_size = 4;
8840 break;
8841 }
8842 return DumpDataExtractor(data, s, byte_offset, format, byte_size,
8843 item_count, UINT32_MAX, LLDB_INVALID_ADDRESS,
8844 bitfield_bit_size, bitfield_bit_offset,
8845 exe_scope);
8846 }
8847 break;
8848 }
8849 }
8850 return false;
8851}
8852
8853void TypeSystemClang::DumpSummary(lldb::opaque_compiler_type_t type,
8854 ExecutionContext *exe_ctx, Stream *s,
8855 const lldb_private::DataExtractor &data,
8856 lldb::offset_t data_byte_offset,
8857 size_t data_byte_size) {
8858 uint32_t length = 0;
8859 if (IsCStringType(type, length)) {
8860 if (exe_ctx) {
8861 Process *process = exe_ctx->GetProcessPtr();
8862 if (process) {
8863 lldb::offset_t offset = data_byte_offset;
8864 lldb::addr_t pointer_address = data.GetMaxU64(&offset, data_byte_size);
8865 std::vector<uint8_t> buf;
8866 if (length > 0)
8867 buf.resize(length);
8868 else
8869 buf.resize(256);
8870
8871 DataExtractor cstr_data(&buf.front(), buf.size(),
8872 process->GetByteOrder(), 4);
8873 buf.back() = '\0';
8874 size_t bytes_read;
8875 size_t total_cstr_len = 0;
8876 Status error;
8877 while ((bytes_read = process->ReadMemory(pointer_address, &buf.front(),
8878 buf.size(), error)) > 0) {
8879 const size_t len = strlen((const char *)&buf.front());
8880 if (len == 0)
8881 break;
8882 if (total_cstr_len == 0)
8883 s->PutCString(" \"");
8884 DumpDataExtractor(cstr_data, s, 0, lldb::eFormatChar, 1, len,
8885 UINT32_MAX, LLDB_INVALID_ADDRESS, 0, 0);
8886 total_cstr_len += len;
8887 if (len < buf.size())
8888 break;
8889 pointer_address += total_cstr_len;
8890 }
8891 if (total_cstr_len > 0)
8892 s->PutChar('"');
8893 }
8894 }
8895 }
8896}
8897
8898void TypeSystemClang::DumpTypeDescription(lldb::opaque_compiler_type_t type,
8899 lldb::DescriptionLevel level) {
8900 StreamFile s(stdout, false);
8901 DumpTypeDescription(type, &s, level);
8902
8903 CompilerType ct(this, type);
8904 const clang::Type *clang_type = ClangUtil::GetQualType(ct).getTypePtr();
8905 ClangASTMetadata *metadata = GetMetadata(clang_type);
8906 if (metadata) {
8907 metadata->Dump(&s);
8908 }
8909}
8910
8911void TypeSystemClang::DumpTypeDescription(lldb::opaque_compiler_type_t type,
8912 Stream *s,
8913 lldb::DescriptionLevel level) {
8914 if (type) {
8915 clang::QualType qual_type =
8916 RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef});
8917
8918 llvm::SmallVector<char, 1024> buf;
8919 llvm::raw_svector_ostream llvm_ostrm(buf);
8920
8921 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
8922 switch (type_class) {
8923 case clang::Type::ObjCObject:
8924 case clang::Type::ObjCInterface: {
8925 GetCompleteType(type);
8926
8927 auto *objc_class_type =
8928 llvm::dyn_cast<clang::ObjCObjectType>(qual_type.getTypePtr());
8929 assert(objc_class_type);
8930 if (!objc_class_type)
8931 break;
8932 clang::ObjCInterfaceDecl *class_interface_decl =
8933 objc_class_type->getInterface();
8934 if (!class_interface_decl)
8935 break;
8936 if (level == eDescriptionLevelVerbose)
8937 class_interface_decl->dump(llvm_ostrm);
8938 else
8939 class_interface_decl->print(llvm_ostrm,
8940 getASTContext().getPrintingPolicy(),
8941 s->GetIndentLevel());
8942 } break;
8943
8944 case clang::Type::Typedef: {
8945 auto *typedef_type = qual_type->getAs<clang::TypedefType>();
8946 if (!typedef_type)
8947 break;
8948 const clang::TypedefNameDecl *typedef_decl = typedef_type->getDecl();
8949 if (level == eDescriptionLevelVerbose)
8950 typedef_decl->dump(llvm_ostrm);
8951 else {
8952 std::string clang_typedef_name(GetTypeNameForDecl(typedef_decl));
8953 if (!clang_typedef_name.empty()) {
8954 s->PutCString("typedef ");
8955 s->PutCString(clang_typedef_name);
8956 }
8957 }
8958 } break;
8959
8960 case clang::Type::Record: {
8961 GetCompleteType(type);
8962
8963 auto *record_type = llvm::cast<clang::RecordType>(qual_type.getTypePtr());
8964 const clang::RecordDecl *record_decl = record_type->getDecl();
8965 if (level == eDescriptionLevelVerbose)
8966 record_decl->dump(llvm_ostrm);
8967 else {
8968 if (auto *cxx_record_decl =
8969 llvm::dyn_cast<clang::CXXRecordDecl>(record_decl))
8970 cxx_record_decl->print(llvm_ostrm,
8971 getASTContext().getPrintingPolicy(),
8972 s->GetIndentLevel());
8973 else
8974 record_decl->print(llvm_ostrm, getASTContext().getPrintingPolicy(),
8975 s->GetIndentLevel());
8976 }
8977 } break;
8978
8979 default: {
8980 if (auto *tag_type =
8981 llvm::dyn_cast<clang::TagType>(qual_type.getTypePtr())) {
8982 if (clang::TagDecl *tag_decl = tag_type->getDecl()) {
8983 if (level == eDescriptionLevelVerbose)
8984 tag_decl->dump(llvm_ostrm);
8985 else
8986 tag_decl->print(llvm_ostrm, 0);
8987 }
8988 } else {
8989 if (level == eDescriptionLevelVerbose)
8990 qual_type->dump(llvm_ostrm, getASTContext());
8991 else {
8992 std::string clang_type_name(qual_type.getAsString());
8993 if (!clang_type_name.empty())
8994 s->PutCString(clang_type_name);
8995 }
8996 }
8997 }
8998 }
8999
9000 if (buf.size() > 0) {
9001 s->Write(buf.data(), buf.size());
9002 }
9003}
9004}
9005
9006void TypeSystemClang::DumpTypeName(const CompilerType &type) {
9007 if (ClangUtil::IsClangType(type)) {
9008 clang::QualType qual_type(
9009 ClangUtil::GetCanonicalQualType(ClangUtil::RemoveFastQualifiers(type)));
9010
9011 const clang::Type::TypeClass type_class = qual_type->getTypeClass();
9012 switch (type_class) {
9013 case clang::Type::Record: {
9014 const clang::CXXRecordDecl *cxx_record_decl =
9015 qual_type->getAsCXXRecordDecl();
9016 if (cxx_record_decl)
9017 printf("class %s", cxx_record_decl->getName().str().c_str());
9018 } break;
9019
9020 case clang::Type::Enum: {
9021 clang::EnumDecl *enum_decl =
9022 llvm::cast<clang::EnumType>(qual_type)->getDecl();
9023 if (enum_decl) {
9024 printf("enum %s", enum_decl->getName().str().c_str());
9025 }
9026 } break;
9027
9028 case clang::Type::ObjCObject:
9029 case clang::Type::ObjCInterface: {
9030 const clang::ObjCObjectType *objc_class_type =
9031 llvm::dyn_cast<clang::ObjCObjectType>(qual_type);
9032 if (objc_class_type) {
9033 clang::ObjCInterfaceDecl *class_interface_decl =
9034 objc_class_type->getInterface();
9035 // We currently can't complete objective C types through the newly
9036 // added ASTContext because it only supports TagDecl objects right
9037 // now...
9038 if (class_interface_decl)
9039 printf("@class %s", class_interface_decl->getName().str().c_str());
9040 }
9041 } break;
9042
9043 case clang::Type::Typedef:
9044 printf("typedef %s", llvm::cast<clang::TypedefType>(qual_type)
9045 ->getDecl()
9046 ->getName()
9047 .str()
9048 .c_str());
9049 break;
9050
9051 case clang::Type::Auto:
9052 printf("auto ");
9053 return DumpTypeName(CompilerType(type.GetTypeSystem(),
9054 llvm::cast<clang::AutoType>(qual_type)
9055 ->getDeducedType()
9056 .getAsOpaquePtr()));
9057
9058 case clang::Type::Elaborated:
9059 printf("elaborated ");
9060 return DumpTypeName(CompilerType(
9061 type.GetTypeSystem(), llvm::cast<clang::ElaboratedType>(qual_type)
9062 ->getNamedType()
9063 .getAsOpaquePtr()));
9064
9065 case clang::Type::Paren:
9066 printf("paren ");
9067 return DumpTypeName(CompilerType(
9068 type.GetTypeSystem(),
9069 llvm::cast<clang::ParenType>(qual_type)->desugar().getAsOpaquePtr()));
9070
9071 default:
9072 printf("TypeSystemClang::DumpTypeName() type_class = %u", type_class);
9073 break;
9074 }
9075 }
9076}
9077
9078clang::ClassTemplateDecl *TypeSystemClang::ParseClassTemplateDecl(
9079 clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module,
9080 lldb::AccessType access_type, const char *parent_name, int tag_decl_kind,
9081 const TypeSystemClang::TemplateParameterInfos &template_param_infos) {
9082 if (template_param_infos.IsValid()) {
9083 std::string template_basename(parent_name);
9084 template_basename.erase(template_basename.find('<'));
9085
9086 return CreateClassTemplateDecl(decl_ctx, owning_module, access_type,
9087 template_basename.c_str(), tag_decl_kind,
9088 template_param_infos);
9089 }
9090 return nullptr;
9091}
9092
9093void TypeSystemClang::CompleteTagDecl(clang::TagDecl *decl) {
9094 SymbolFile *sym_file = GetSymbolFile();
9095 if (sym_file) {
9096 CompilerType clang_type = GetTypeForDecl(decl);
9097 if (clang_type)
9098 sym_file->CompleteType(clang_type);
9099 }
9100}
9101
9102void TypeSystemClang::CompleteObjCInterfaceDecl(
9103 clang::ObjCInterfaceDecl *decl) {
9104 SymbolFile *sym_file = GetSymbolFile();
9105 if (sym_file) {
9106 CompilerType clang_type = GetTypeForDecl(decl);
9107 if (clang_type)
9108 sym_file->CompleteType(clang_type);
9109 }
9110}
9111
9112DWARFASTParser *TypeSystemClang::GetDWARFParser() {
9113 if (!m_dwarf_ast_parser_up)
9114 m_dwarf_ast_parser_up = std::make_unique<DWARFASTParserClang>(*this);
9115 return m_dwarf_ast_parser_up.get();
9116}
9117
9118PDBASTParser *TypeSystemClang::GetPDBParser() {
9119 if (!m_pdb_ast_parser_up)
9120 m_pdb_ast_parser_up = std::make_unique<PDBASTParser>(*this);
9121 return m_pdb_ast_parser_up.get();
9122}
9123
9124bool TypeSystemClang::LayoutRecordType(
9125 const clang::RecordDecl *record_decl, uint64_t &bit_size,
9126 uint64_t &alignment,
9127 llvm::DenseMap<const clang::FieldDecl *, uint64_t> &field_offsets,
9128 llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
9129 &base_offsets,
9130 llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>
9131 &vbase_offsets) {
9132 lldb_private::ClangASTImporter *importer = nullptr;
9133 if (m_dwarf_ast_parser_up)
9134 importer = &m_dwarf_ast_parser_up->GetClangASTImporter();
9135 if (!importer && m_pdb_ast_parser_up)
9136 importer = &m_pdb_ast_parser_up->GetClangASTImporter();
9137 if (!importer)
9138 return false;
9139
9140 return importer->LayoutRecordType(record_decl, bit_size, alignment,
9141 field_offsets, base_offsets, vbase_offsets);
9142}
9143
9144// CompilerDecl override functions
9145
9146ConstString TypeSystemClang::DeclGetName(void *opaque_decl) {
9147 if (opaque_decl) {
9148 clang::NamedDecl *nd =
9149 llvm::dyn_cast<NamedDecl>((clang::Decl *)opaque_decl);
9150 if (nd != nullptr)
9151 return ConstString(nd->getDeclName().getAsString());
9152 }
9153 return ConstString();
9154}
9155
9156ConstString TypeSystemClang::DeclGetMangledName(void *opaque_decl) {
9157 if (opaque_decl) {
9158 clang::NamedDecl *nd =
9159 llvm::dyn_cast<clang::NamedDecl>((clang::Decl *)opaque_decl);
9160 if (nd != nullptr && !llvm::isa<clang::ObjCMethodDecl>(nd)) {
9161 clang::MangleContext *mc = getMangleContext();
9162 if (mc && mc->shouldMangleCXXName(nd)) {
9163 llvm::SmallVector<char, 1024> buf;
9164 llvm::raw_svector_ostream llvm_ostrm(buf);
9165 if (llvm::isa<clang::CXXConstructorDecl>(nd)) {
9166 mc->mangleName(
9167 clang::GlobalDecl(llvm::dyn_cast<clang::CXXConstructorDecl>(nd),
9168 Ctor_Complete),
9169 llvm_ostrm);
9170 } else if (llvm::isa<clang::CXXDestructorDecl>(nd)) {
9171 mc->mangleName(
9172 clang::GlobalDecl(llvm::dyn_cast<clang::CXXDestructorDecl>(nd),
9173 Dtor_Complete),
9174 llvm_ostrm);
9175 } else {
9176 mc->mangleName(nd, llvm_ostrm);
9177 }
9178 if (buf.size() > 0)
9179 return ConstString(buf.data(), buf.size());
9180 }
9181 }
9182 }
9183 return ConstString();
9184}
9185
9186CompilerDeclContext TypeSystemClang::DeclGetDeclContext(void *opaque_decl) {
9187 if (opaque_decl)
9188 return CreateDeclContext(((clang::Decl *)opaque_decl)->getDeclContext());
9189 return CompilerDeclContext();
9190}
9191
9192CompilerType TypeSystemClang::DeclGetFunctionReturnType(void *opaque_decl) {
9193 if (clang::FunctionDecl *func_decl =
9194 llvm::dyn_cast<clang::FunctionDecl>((clang::Decl *)opaque_decl))
9195 return GetType(func_decl->getReturnType());
9196 if (clang::ObjCMethodDecl *objc_method =
9197 llvm::dyn_cast<clang::ObjCMethodDecl>((clang::Decl *)opaque_decl))
9198 return GetType(objc_method->getReturnType());
9199 else
9200 return CompilerType();
9201}
9202
9203size_t TypeSystemClang::DeclGetFunctionNumArguments(void *opaque_decl) {
9204 if (clang::FunctionDecl *func_decl =
9205 llvm::dyn_cast<clang::FunctionDecl>((clang::Decl *)opaque_decl))
9206 return func_decl->param_size();
9207 if (clang::ObjCMethodDecl *objc_method =
9208 llvm::dyn_cast<clang::ObjCMethodDecl>((clang::Decl *)opaque_decl))
9209 return objc_method->param_size();
9210 else
9211 return 0;
9212}
9213
9214CompilerType TypeSystemClang::DeclGetFunctionArgumentType(void *opaque_decl,
9215 size_t idx) {
9216 if (clang::FunctionDecl *func_decl =
9217 llvm::dyn_cast<clang::FunctionDecl>((clang::Decl *)opaque_decl)) {
9218 if (idx < func_decl->param_size()) {
9219 ParmVarDecl *var_decl = func_decl->getParamDecl(idx);
9220 if (var_decl)
9221 return GetType(var_decl->getOriginalType());
9222 }
9223 } else if (clang::ObjCMethodDecl *objc_method =
9224 llvm::dyn_cast<clang::ObjCMethodDecl>(
9225 (clang::Decl *)opaque_decl)) {
9226 if (idx < objc_method->param_size())
9227 return GetType(objc_method->parameters()[idx]->getOriginalType());
9228 }
9229 return CompilerType();
9230}
9231
9232// CompilerDeclContext functions
9233
9234std::vector<CompilerDecl> TypeSystemClang::DeclContextFindDeclByName(
9235 void *opaque_decl_ctx, ConstString name, const bool ignore_using_decls) {
9236 std::vector<CompilerDecl> found_decls;
9237 if (opaque_decl_ctx) {
9238 DeclContext *root_decl_ctx = (DeclContext *)opaque_decl_ctx;
9239 std::set<DeclContext *> searched;
9240 std::multimap<DeclContext *, DeclContext *> search_queue;
9241 SymbolFile *symbol_file = GetSymbolFile();
9242
9243 for (clang::DeclContext *decl_context = root_decl_ctx;
9244 decl_context != nullptr && found_decls.empty();
9245 decl_context = decl_context->getParent()) {
9246 search_queue.insert(std::make_pair(decl_context, decl_context));
9247
9248 for (auto it = search_queue.find(decl_context); it != search_queue.end();
9249 it++) {
9250 if (!searched.insert(it->second).second)
9251 continue;
9252 symbol_file->ParseDeclsForContext(
9253 CreateDeclContext(it->second));
9254
9255 for (clang::Decl *child : it->second->decls()) {
9256 if (clang::UsingDirectiveDecl *ud =
9257 llvm::dyn_cast<clang::UsingDirectiveDecl>(child)) {
9258 if (ignore_using_decls)
9259 continue;
9260 clang::DeclContext *from = ud->getCommonAncestor();
9261 if (searched.find(ud->getNominatedNamespace()) == searched.end())
9262 search_queue.insert(
9263 std::make_pair(from, ud->getNominatedNamespace()));
9264 } else if (clang::UsingDecl *ud =
9265 llvm::dyn_cast<clang::UsingDecl>(child)) {
9266 if (ignore_using_decls)
9267 continue;
9268 for (clang::UsingShadowDecl *usd : ud->shadows()) {
9269 clang::Decl *target = usd->getTargetDecl();
9270 if (clang::NamedDecl *nd =
9271 llvm::dyn_cast<clang::NamedDecl>(target)) {
9272 IdentifierInfo *ii = nd->getIdentifier();
9273 if (ii != nullptr &&
9274 ii->getName().equals(name.AsCString(nullptr)))
9275 found_decls.push_back(GetCompilerDecl(nd));
9276 }
9277 }
9278 } else if (clang::NamedDecl *nd =
9279 llvm::dyn_cast<clang::NamedDecl>(child)) {
9280 IdentifierInfo *ii = nd->getIdentifier();
9281 if (ii != nullptr && ii->getName().equals(name.AsCString(nullptr)))
9282 found_decls.push_back(GetCompilerDecl(nd));
9283 }
9284 }
9285 }
9286 }
9287 }
9288 return found_decls;
9289}
9290
9291// Look for child_decl_ctx's lookup scope in frame_decl_ctx and its parents,
9292// and return the number of levels it took to find it, or
9293// LLDB_INVALID_DECL_LEVEL if not found. If the decl was imported via a using
9294// declaration, its name and/or type, if set, will be used to check that the
9295// decl found in the scope is a match.
9296//
9297// The optional name is required by languages (like C++) to handle using
9298// declarations like:
9299//
9300// void poo();
9301// namespace ns {
9302// void foo();
9303// void goo();
9304// }
9305// void bar() {
9306// using ns::foo;
9307// // CountDeclLevels returns 0 for 'foo', 1 for 'poo', and
9308// // LLDB_INVALID_DECL_LEVEL for 'goo'.
9309// }
9310//
9311// The optional type is useful in the case that there's a specific overload
9312// that we're looking for that might otherwise be shadowed, like:
9313//
9314// void foo(int);
9315// namespace ns {
9316// void foo();
9317// }
9318// void bar() {
9319// using ns::foo;
9320// // CountDeclLevels returns 0 for { 'foo', void() },
9321// // 1 for { 'foo', void(int) }, and
9322// // LLDB_INVALID_DECL_LEVEL for { 'foo', void(int, int) }.
9323// }
9324//
9325// NOTE: Because file statics are at the TranslationUnit along with globals, a
9326// function at file scope will return the same level as a function at global
9327// scope. Ideally we'd like to treat the file scope as an additional scope just
9328// below the global scope. More work needs to be done to recognise that, if
9329// the decl we're trying to look up is static, we should compare its source
9330// file with that of the current scope and return a lower number for it.
9331uint32_t TypeSystemClang::CountDeclLevels(clang::DeclContext *frame_decl_ctx,
9332 clang::DeclContext *child_decl_ctx,
9333 ConstString *child_name,
9334 CompilerType *child_type) {
9335 if (frame_decl_ctx) {
9336 std::set<DeclContext *> searched;
9337 std::multimap<DeclContext *, DeclContext *> search_queue;
9338 SymbolFile *symbol_file = GetSymbolFile();
9339
9340 // Get the lookup scope for the decl we're trying to find.
9341 clang::DeclContext *parent_decl_ctx = child_decl_ctx->getParent();
9342
9343 // Look for it in our scope's decl context and its parents.
9344 uint32_t level = 0;
9345 for (clang::DeclContext *decl_ctx = frame_decl_ctx; decl_ctx != nullptr;
9346 decl_ctx = decl_ctx->getParent()) {
9347 if (!decl_ctx->isLookupContext())
9348 continue;
9349 if (decl_ctx == parent_decl_ctx)
9350 // Found it!
9351 return level;
9352 search_queue.insert(std::make_pair(decl_ctx, decl_ctx));
9353 for (auto it = search_queue.find(decl_ctx); it != search_queue.end();
9354 it++) {
9355 if (searched.find(it->second) != searched.end())
9356 continue;
9357
9358 // Currently DWARF has one shared translation unit for all Decls at top
9359 // level, so this would erroneously find using statements anywhere. So
9360 // don't look at the top-level translation unit.
9361 // TODO fix this and add a testcase that depends on it.
9362
9363 if (llvm::isa<clang::TranslationUnitDecl>(it->second))
9364 continue;
9365
9366 searched.insert(it->second);
9367 symbol_file->ParseDeclsForContext(
9368 CreateDeclContext(it->second));
9369
9370 for (clang::Decl *child : it->second->decls()) {
9371 if (clang::UsingDirectiveDecl *ud =
9372 llvm::dyn_cast<clang::UsingDirectiveDecl>(child)) {
9373 clang::DeclContext *ns = ud->getNominatedNamespace();
9374 if (ns == parent_decl_ctx)
9375 // Found it!
9376 return level;
9377 clang::DeclContext *from = ud->getCommonAncestor();
9378 if (searched.find(ns) == searched.end())
9379 search_queue.insert(std::make_pair(from, ns));
9380 } else if (child_name) {
9381 if (clang::UsingDecl *ud =
9382 llvm::dyn_cast<clang::UsingDecl>(child)) {
9383 for (clang::UsingShadowDecl *usd : ud->shadows()) {
9384 clang::Decl *target = usd->getTargetDecl();
9385 clang::NamedDecl *nd = llvm::dyn_cast<clang::NamedDecl>(target);
9386 if (!nd)
9387 continue;
9388 // Check names.
9389 IdentifierInfo *ii = nd->getIdentifier();
9390 if (ii == nullptr ||
9391 !ii->getName().equals(child_name->AsCString(nullptr)))
9392 continue;
9393 // Check types, if one was provided.
9394 if (child_type) {
9395 CompilerType clang_type = GetTypeForDecl(nd);
9396 if (!AreTypesSame(clang_type, *child_type,
9397 /*ignore_qualifiers=*/true))
9398 continue;
9399 }
9400 // Found it!
9401 return level;
9402 }
9403 }
9404 }
9405 }
9406 }
9407 ++level;
9408 }
9409 }
9410 return LLDB_INVALID_DECL_LEVEL;
9411}
9412
9413ConstString TypeSystemClang::DeclContextGetName(void *opaque_decl_ctx) {
9414 if (opaque_decl_ctx) {
9415 clang::NamedDecl *named_decl =
9416 llvm::dyn_cast<clang::NamedDecl>((clang::DeclContext *)opaque_decl_ctx);
9417 if (named_decl)
9418 return ConstString(named_decl->getName());
9419 }
9420 return ConstString();
9421}
9422
9423ConstString
9424TypeSystemClang::DeclContextGetScopeQualifiedName(void *opaque_decl_ctx) {
9425 if (opaque_decl_ctx) {
9426 clang::NamedDecl *named_decl =
9427 llvm::dyn_cast<clang::NamedDecl>((clang::DeclContext *)opaque_decl_ctx);
9428 if (named_decl)
9429 return ConstString(GetTypeNameForDecl(named_decl));
9430 }
9431 return ConstString();
9432}
9433
9434bool TypeSystemClang::DeclContextIsClassMethod(
9435 void *opaque_decl_ctx, lldb::LanguageType *language_ptr,
9436 bool *is_instance_method_ptr, ConstString *language_object_name_ptr) {
9437 if (opaque_decl_ctx) {
9438 clang::DeclContext *decl_ctx = (clang::DeclContext *)opaque_decl_ctx;
9439 if (ObjCMethodDecl *objc_method =
9440 llvm::dyn_cast<clang::ObjCMethodDecl>(decl_ctx)) {
9441 if (is_instance_method_ptr)
9442 *is_instance_method_ptr = objc_method->isInstanceMethod();
9443 if (language_ptr)
9444 *language_ptr = eLanguageTypeObjC;
9445 if (language_object_name_ptr)
9446 language_object_name_ptr->SetCString("self");
9447 return true;
9448 } else if (CXXMethodDecl *cxx_method =
9449 llvm::dyn_cast<clang::CXXMethodDecl>(decl_ctx)) {
9450 if (is_instance_method_ptr)
9451 *is_instance_method_ptr = cxx_method->isInstance();
9452 if (language_ptr)
9453 *language_ptr = eLanguageTypeC_plus_plus;
9454 if (language_object_name_ptr)
9455 language_object_name_ptr->SetCString("this");
9456 return true;
9457 } else if (clang::FunctionDecl *function_decl =
9458 llvm::dyn_cast<clang::FunctionDecl>(decl_ctx)) {
9459 ClangASTMetadata *metadata = GetMetadata(function_decl);
9460 if (metadata && metadata->HasObjectPtr()) {
9461 if (is_instance_method_ptr)
9462 *is_instance_method_ptr = true;
9463 if (language_ptr)
9464 *language_ptr = eLanguageTypeObjC;
9465 if (language_object_name_ptr)
9466 language_object_name_ptr->SetCString(metadata->GetObjectPtrName());
9467 return true;
9468 }
9469 }
9470 }
9471 return false;
9472}
9473
9474bool TypeSystemClang::DeclContextIsContainedInLookup(
9475 void *opaque_decl_ctx, void *other_opaque_decl_ctx) {
9476 auto *decl_ctx = (clang::DeclContext *)opaque_decl_ctx;
9477 auto *other = (clang::DeclContext *)other_opaque_decl_ctx;
9478
9479 do {
9480 // A decl context always includes its own contents in its lookup.
9481 if (decl_ctx == other)
9482 return true;
9483
9484 // If we have an inline namespace, then the lookup of the parent context
9485 // also includes the inline namespace contents.
9486 } while (other->isInlineNamespace() && (other = other->getParent()));
9487
9488 return false;
9489}
9490
9491static bool IsClangDeclContext(const CompilerDeclContext &dc) {
9492 return dc.IsValid() && isa<TypeSystemClang>(dc.GetTypeSystem());
9493}
9494
9495clang::DeclContext *
9496TypeSystemClang::DeclContextGetAsDeclContext(const CompilerDeclContext &dc) {
9497 if (IsClangDeclContext(dc))
9498 return (clang::DeclContext *)dc.GetOpaqueDeclContext();
9499 return nullptr;
9500}
9501
9502ObjCMethodDecl *
9503TypeSystemClang::DeclContextGetAsObjCMethodDecl(const CompilerDeclContext &dc) {
9504 if (IsClangDeclContext(dc))
9505 return llvm::dyn_cast<clang::ObjCMethodDecl>(
9506 (clang::DeclContext *)dc.GetOpaqueDeclContext());
9507 return nullptr;
9508}
9509
9510CXXMethodDecl *
9511TypeSystemClang::DeclContextGetAsCXXMethodDecl(const CompilerDeclContext &dc) {
9512 if (IsClangDeclContext(dc))
9513 return llvm::dyn_cast<clang::CXXMethodDecl>(
9514 (clang::DeclContext *)dc.GetOpaqueDeclContext());
9515 return nullptr;
9516}
9517
9518clang::FunctionDecl *
9519TypeSystemClang::DeclContextGetAsFunctionDecl(const CompilerDeclContext &dc) {
9520 if (IsClangDeclContext(dc))
9521 return llvm::dyn_cast<clang::FunctionDecl>(
9522 (clang::DeclContext *)dc.GetOpaqueDeclContext());
9523 return nullptr;
9524}
9525
9526clang::NamespaceDecl *
9527TypeSystemClang::DeclContextGetAsNamespaceDecl(const CompilerDeclContext &dc) {
9528 if (IsClangDeclContext(dc))
9529 return llvm::dyn_cast<clang::NamespaceDecl>(
9530 (clang::DeclContext *)dc.GetOpaqueDeclContext());
9531 return nullptr;
9532}
9533
9534ClangASTMetadata *
9535TypeSystemClang::DeclContextGetMetaData(const CompilerDeclContext &dc,
9536 const Decl *object) {
9537 TypeSystemClang *ast = llvm::cast<TypeSystemClang>(dc.GetTypeSystem());
9538 return ast->GetMetadata(object);
9539}
9540
9541clang::ASTContext *
9542TypeSystemClang::DeclContextGetTypeSystemClang(const CompilerDeclContext &dc) {
9543 TypeSystemClang *ast =
9544 llvm::dyn_cast_or_null<TypeSystemClang>(dc.GetTypeSystem());
9545 if (ast)
9546 return &ast->getASTContext();
9547 return nullptr;
9548}
9549
9550namespace {
9551/// A specialized scratch AST used within ScratchTypeSystemClang.
9552/// These are the ASTs backing the different IsolatedASTKinds. They behave
9553/// like a normal ScratchTypeSystemClang but they don't own their own
9554/// persistent storage or target reference.
9555class SpecializedScratchAST : public TypeSystemClang {
9556public:
9557 /// \param name The display name of the TypeSystemClang instance.
9558 /// \param triple The triple used for the TypeSystemClang instance.
9559 /// \param ast_source The ClangASTSource that should be used to complete
9560 /// type information.
9561 SpecializedScratchAST(llvm::StringRef name, llvm::Triple triple,
9562 std::unique_ptr<ClangASTSource> ast_source)
9563 : TypeSystemClang(name, triple),
9564 m_scratch_ast_source_up(std::move(ast_source)) {
9565 // Setup the ClangASTSource to complete this AST.
9566 m_scratch_ast_source_up->InstallASTContext(*this);
9567 llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> proxy_ast_source(
9568 m_scratch_ast_source_up->CreateProxy());
9569 SetExternalSource(proxy_ast_source);
9570 }
9571
9572 /// The ExternalASTSource that performs lookups and completes types.
9573 std::unique_ptr<ClangASTSource> m_scratch_ast_source_up;
9574};
9575} // namespace
9576
9577char ScratchTypeSystemClang::ID;
9578const llvm::NoneType ScratchTypeSystemClang::DefaultAST = llvm::None;
9579
9580ScratchTypeSystemClang::ScratchTypeSystemClang(Target &target,
9581 llvm::Triple triple)
9582 : TypeSystemClang("scratch ASTContext", triple), m_triple(triple),
9583 m_target_wp(target.shared_from_this()),
9584 m_persistent_variables(new ClangPersistentVariables) {
9585 m_scratch_ast_source_up = CreateASTSource();
9586 m_scratch_ast_source_up->InstallASTContext(*this);
9587 llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> proxy_ast_source(
9588 m_scratch_ast_source_up->CreateProxy());
9589 SetExternalSource(proxy_ast_source);
9590}
9591
9592void ScratchTypeSystemClang::Finalize() {
9593 TypeSystemClang::Finalize();
9594 m_scratch_ast_source_up.reset();
9595}
9596
9597TypeSystemClang *
9598ScratchTypeSystemClang::GetForTarget(Target &target,
9599 llvm::Optional<IsolatedASTKind> ast_kind,
9600 bool create_on_demand) {
9601 auto type_system_or_err = target.GetScratchTypeSystemForLanguage(
9602 lldb::eLanguageTypeC, create_on_demand);
9603 if (auto err = type_system_or_err.takeError()) {
9604 LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET),
9605 std::move(err), "Couldn't get scratch TypeSystemClang");
9606 return nullptr;
9607 }
9608 ScratchTypeSystemClang &scratch_ast =
9609 llvm::cast<ScratchTypeSystemClang>(type_system_or_err.get());
9610 // If no dedicated sub-AST was requested, just return the main AST.
9611 if (ast_kind == DefaultAST)
9612 return &scratch_ast;
9613 // Search the sub-ASTs.
9614 return &scratch_ast.GetIsolatedAST(*ast_kind);
9615}
9616
9617UserExpression *ScratchTypeSystemClang::GetUserExpression(
9618 llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language,
9619 Expression::ResultType desired_type,
9620 const EvaluateExpressionOptions &options, ValueObject *ctx_obj) {
9621 TargetSP target_sp = m_target_wp.lock();
9622 if (!target_sp)
9623 return nullptr;
9624
9625 return new ClangUserExpression(*target_sp.get(), expr, prefix, language,
9626 desired_type, options, ctx_obj);
9627}
9628
9629FunctionCaller *ScratchTypeSystemClang::GetFunctionCaller(
9630 const CompilerType &return_type, const Address &function_address,
9631 const ValueList &arg_value_list, const char *name) {
9632 TargetSP target_sp = m_target_wp.lock();
9633 if (!target_sp)
9634 return nullptr;
9635
9636 Process *process = target_sp->GetProcessSP().get();
9637 if (!process)
9638 return nullptr;
9639
9640 return new ClangFunctionCaller(*process, return_type, function_address,
9641 arg_value_list, name);
9642}
9643
9644std::unique_ptr<UtilityFunction>
9645ScratchTypeSystemClang::CreateUtilityFunction(std::string text,
9646 std::string name) {
9647 TargetSP target_sp = m_target_wp.lock();
9648 if (!target_sp)
9649 return {};
9650
9651 return std::make_unique<ClangUtilityFunction>(
9652 *target_sp.get(), std::move(text), std::move(name));
9653}
9654
9655PersistentExpressionState *
9656ScratchTypeSystemClang::GetPersistentExpressionState() {
9657 return m_persistent_variables.get();
9658}
9659
9660void ScratchTypeSystemClang::ForgetSource(ASTContext *src_ctx,
9661 ClangASTImporter &importer) {
9662 // Remove it as a source from the main AST.
9663 importer.ForgetSource(&getASTContext(), src_ctx);
9664 // Remove it as a source from all created sub-ASTs.
9665 for (const auto &a : m_isolated_asts)
9666 importer.ForgetSource(&a.second->getASTContext(), src_ctx);
9667}
9668
9669std::unique_ptr<ClangASTSource> ScratchTypeSystemClang::CreateASTSource() {
9670 return std::make_unique<ClangASTSource>(
9671 m_target_wp.lock()->shared_from_this(),
9672 m_persistent_variables->GetClangASTImporter());
9673}
9674
9675static llvm::StringRef
9676GetSpecializedASTName(ScratchTypeSystemClang::IsolatedASTKind feature) {
9677 switch (feature) {
9678 case ScratchTypeSystemClang::IsolatedASTKind::CppModules:
9679 return "scratch ASTContext for C++ module types";
9680 }
9681 llvm_unreachable("Unimplemented ASTFeature kind?");
9682}
9683
9684TypeSystemClang &ScratchTypeSystemClang::GetIsolatedAST(
9685 ScratchTypeSystemClang::IsolatedASTKind feature) {
9686 auto found_ast = m_isolated_asts.find(feature);
9687 if (found_ast != m_isolated_asts.end())
9688 return *found_ast->second;
9689
9690 // Couldn't find the requested sub-AST, so create it now.
9691 std::unique_ptr<TypeSystemClang> new_ast;
9692 new_ast.reset(new SpecializedScratchAST(GetSpecializedASTName(feature),
9693 m_triple, CreateASTSource()));
9694 m_isolated_asts[feature] = std::move(new_ast);
9695 return *m_isolated_asts[feature];
9696}
9697